Reputation: 55210
I have an AJAX call which returns a string
which ideally should be an array of arrays
var jsonString = "[['name1', 30, 20], ['name2', 10, 100], ['name3', 140, 130]]";
This is what I get returned. I would like to convert it to an array of arrays
var jsonArray = [['name1', 30, 20], ['name2', 10, 100], ['name3', 140, 130]];
Obviously string.split(",")
wont work and gives me an array with 9 elements.
How do I parse this?
My fiddle: http://jsfiddle.net/codovations/hgLJh/
Upvotes: 0
Views: 1494
Reputation: 122906
With this string you could use: JSON.parse(jsonString.replace(/'/g,'"'))
.
Upvotes: 1
Reputation: 2610
naveen I checked your string and if you are sure your string have ' instead of " in array elements, you can replace them with " and then you can just parse them as json:
JSON.parse('[["name1", 30, 20], ["name2", 10, 100], ["name3", 140, 130]]');
returns array of arrays.
Regards.
Upvotes: 2
Reputation: 38345
Use the JSON.parse()
function:
var jsonArray = JSON.parse(jsonString);
Though note that this will only work if the string you're passing to it is valid JSON. What you've provided isn't - JSON strings are wrapped in double-quotes, not single.
Upvotes: 1