Convert JSON string to array of JSON objects in Javascript
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
Using jQuery:
var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
var jsonObj = $.parseJSON('[' + str + ']');
jsonObj
is your JSON object.
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..
As simple as that.
var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
dataObj = JSON.parse(str);