Convert JSON string to array of JSON objects in Javascript

JavascriptArraysJson

Javascript Problem Overview


I would like to convert this string

{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}

to array of 2 JSON objects. How should I do it?

best

Javascript Solutions


Solution 1 - Javascript

Using jQuery:

var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
var jsonObj = $.parseJSON('[' + str + ']');

jsonObj is your JSON object.

Solution 2 - Javascript

As simple as that.

var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
 dataObj = JSON.parse(str);

Solution 3 - Javascript

As Luca indicated, add extra [] to your string and use the code below:

var myObject = eval('(' + myJSONtext + ')');

to test it you can use the snippet below.

var s =" [{'id':1,'name':'Test1'},{'id':2,'name':'Test2'}]";
var myObject = eval('(' + s + ')');
for (i in myObject)
{
   alert(myObject[i]["name"]);
}

hope it helps..

Solution 4 - Javascript

Append extra an [ and ] to the beginning and end of the string. This will make it an array. Then use eval() or some safe JSON serializer to serialize the string and make it a real JavaScript datatype.

You should use https://github.com/douglascrockford/JSON-js instead of eval(). eval is only if you're doing some quick debugging/testing.

Solution 5 - Javascript

If your using jQuery, it's parseJSON function can be used and is preferable to JavaScript's native eval() function.

Solution 6 - Javascript

I know a lot of people are saying use eval. the eval() js function will call the compiler, and that can offer a series of security risks. It is best to avoid its usage where possible. The parse function offers a more secure alternative.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSobisView Question on Stackoverflow
Solution 1 - JavascriptdariooView Answer on Stackoverflow
Solution 2 - JavascriptGyanesh GourawView Answer on Stackoverflow
Solution 3 - JavascriptAnarchistGeekView Answer on Stackoverflow
Solution 4 - JavascriptLuca MatteisView Answer on Stackoverflow
Solution 5 - JavascriptgreenimpalaView Answer on Stackoverflow
Solution 6 - JavascriptSteveView Answer on Stackoverflow