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 ?

Arkar Aung
  • 3,554
  • 1
  • 16
  • 25
ninja.stop
  • 410
  • 1
  • 10
  • 24

2 Answers2

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

Andy
  • 61,948
  • 13
  • 68
  • 95
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);
Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101