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
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.
JSON.parse has been part of the "standard built-in" objects for several years now.As simple as that.
var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
dataObj = JSON.parse(str);
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..
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.
If your using jQuery, it's parseJSON function can be used and is preferable to JavaScript's native eval() function.