Reputation: 1400
Right now I have ajax call that returns me this:
"nodes":
[
{"ID":"87","score":"-0.2","dscore":"-0.4","x":"250","y":"250","name":"TEST","ticker":"TEST","datafrom":"0000-00-00","r":"28","fixed":"true","color":"grey"}
]
When I need this
"nodes":
[
{"ID":"87","score":"-0.2","dscore":"-0.4","x":250,"y":250,"name":"TEST","ticker":"TEST","datafrom":"0000-00-00","r":"28","fixed":"true","color":"grey"}
]
So the real difference is between "x"
and "y"
values, first example they have double quotes, second they don't. I'm using this for d3.js
so it needs to be without quotes, and I'm pulling a lot of that, that was just one line. So I can parse this via php/ajax/javascript, whatever is the most efficient. How would I go on about parsing the entire thing though?
edit: I said php since I use php to grab this info from the database, after which I do json_encode($str)
, so it's parase-able there as well.
Upvotes: 1
Views: 252
Reputation: 303
The issue here is that when source data is json-encoded, all fields in nodes
array have "string" type, and so json encoder encodes them as strings, with quotes.
The most correct way to fix this would be assigning correct types to source data, so then json encoder would encode it as numbers, with quotes.
If you have any control on the side that generates json you get in reply, then just intval
/floatval
the numbers before you json-encode them.
If you don't have it, then convert it on js side, before passing to d3. Use parseInt(nodes[i].x, 10)
or parseFloat(nodes[i].y, 10)
, depending on what type of values x
and y
should contain. When converting strings to numbers in JS it is always important to specify second param "radix", or your numbers might be interpreted with some JS engines as octal if they begin with 0. See MDN for more information.
For the reference:
$ php -r '$a = ["test" => "1.25"]; echo json_encode($a) . PHP_EOL;'
{"test":"1.25"}
^
$ php -r '$a = ["test" => 1.25]; echo json_encode($a) . PHP_EOL;'
{"test":1.25}
^
Upvotes: 1
Reputation: 3260
You can use parseInt to convert the string value to an integer.
var x = parseInt(jsonObj.get("x"), 10);
The 10 is to use base 10 when parsing.
Upvotes: 1