0

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/

3 Answers 3

2

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.

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

1 Comment

cool. i could just do a string.replace and make it work. oh the nuances of javascript...
1

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.

13 Comments

you are just repeating what i have written in my fiddle. :)
Yep, invalid JSON. Well spot!
@naveen - Your fiddle suggests that you are using jQuery and that you already know the answer. What's the point of asking?
@naveen I didn't even notice that there was a jsFiddle, I stopped reading as soon as I'd seen enough to know the answer to the question. You need to use JSON.parse() and provide valid JSON; if you knew the first part, the second is where you're going wrong.
@naveen You'll need to change the server-side code handling the AJAX call to return valid JSON, because what you're currently getting returned is invalid and therefore unusable. JSON is the format for representing JavaScript objects (and arrays) as strings, but it has a very strict specification that you have to meet.
|
1

With this string you could use: JSON.parse(jsonString.replace(/'/g,'"')).

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.