2

I am making a asynchronous request to my server and its returning an array as a string. The string is in the proper array form for example:

"[{"spo":"I"},{"spo":"hate"},{"spo":"computers"}]"

Is there a way to simply create an array from this string?

1
  • The builtin JSON function is best if available, you can also use eval: var x = '[1,2,3]';alert(eval(x));. That's how it was done in pre-JSON browsers. Commented Jul 8, 2011 at 8:41

3 Answers 3

7

That's a JSON string, you can create an array from it with:

JSON.parse('[{"spo":"I"},{"spo":"hate"},{"spo":"computers"}]')

In older browsers you may need to include the json2.js.

3
  • 1
    JSON.parse will return an Array object? Commented Jul 8, 2011 at 8:05
  • 1
    Yes it does, if the provided string is an encoded array which now is. Commented Jul 8, 2011 at 8:05
  • My issue come from IE6. Fixed it as soon as I got you hint. Commented Jul 8, 2011 at 8:11
3

If you use jQuery, you can get it as array by specifying the dataType as Json. See jQuery.getJSON()

3
  • Same as in Mootools and includes support for IE6 Commented Jul 8, 2011 at 8:14
  • 1
    Cool, include a 90k script to do something that can be done with built-in functions. Commented Jul 8, 2011 at 8:40
  • I meant to say if they are using jQuery. And jQuery is not 90k, just 31KB (minified). Commented Jul 8, 2011 at 10:03
0

The string happens to correspond to the JSON format, so you can use a JSON parser to turn it into an array, for example the JSON parser in jQuery:

var myLittleArray = $.parseJSON(theJsonString);

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.