Convert a JSON string to an array of JSON objects in Javascript

I would like to convert this line

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

into an array of two JSON objects. How should I do it?

better

+45
json javascript arrays
Dec 07 '10 at 10:18
source share
6 answers

Using jQuery:

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

jsonObj is your JSON object.

+81
Dec 07 '10 at 10:37
source share

As Luca pointed out, add an extra line [] to your line and use the following code:

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

to check 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 this helps.

+22
Dec 07 '10 at
source share

The easiest way.

 var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}'; dataObj = JSON.parse(str); 
+12
Mar 10
source share

Add extra [ and ] to the beginning and end of the line. This will make an array. Then use eval() or some secure JSON serializer to serialize the string and make it a real JavaScript data type.

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

+5
Dec 07 '10 at 10:20
source share

If you use jQuery, you can use the parseJSON function and it is preferable to use the built-in eval() function for JavaScript.

+4
Dec 07 '10 at
source share

I know that many people talk about using eval. the eval () js function will call the compiler and may offer a number of security risks. It is best to avoid using it where possible. The parse function offers a safer alternative.

+1
Jun 06 2018-12-06T00:
source share



All Articles