1

I am having one JSON as :

{\"A\":\"1.354534634,\",\"B\":\"-0.432335,\",\"C\":\"0.234123423,\"}

I need to tokenize this with Javascript and I need to assign values like that:

Accel_X = value of A, ie. 1.354534634

Accel_Y = value of B, ie. -0.432335

Accel_Z = value of C, ie. 0.234123423

I can use slice() . But that is a bad way to do that for a larger instance and not good way to code. So, How can I do that ?

1
  • 4
    why cant you JSON.parse it? Commented Sep 16, 2014 at 10:58

2 Answers 2

4

You don't need to escape those quote marks in the JSON for a start:

var json = '{"A":"1.354534634,","B":"-0.432335,","C":"0.234123423,"}';

Parse it:

var obj = JSON.parse(json);

Then just assign to your variables, removing the commas.

var Accel_X = obj.A.replace(',', '');
var Accel_Y = obj.B.replace(',', '');
var Accel_Z = obj.C.replace(',', '');

Note: this will assign the numbers as strings. If you want them as floating point numbers you need to do a type conversion too:

var Accel_X = parseFloat(obj.A.replace(',', ''));
var Accel_Y = parseFloat(obj.B.replace(',', ''));
var Accel_Z = parseFloat(obj.C.replace(',', ''));

DEMO

Sign up to request clarification or add additional context in comments.

Comments

2

You can use JSON.parse for it.

var a = "{\"A\":\"1.354534634,\",\"B\":\"-0.432335,\",\"C\":\"0.234123423,\"}";

var b = JSON.parse(a);

Accel_X = b.A;
Accel_Y = b.B;
Accel_Z = b.C;

console.log(Accel_X,Accel_Y,Accel_Z);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.