71

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

1
  • 3
    If you get this as a JSON string, then it is not valid JSON anyway... where do you get it from? Could you post a more complete code example? Commented Dec 7, 2010 at 10:22

6 Answers 6

97

Using jQuery:

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

jsonObj is your JSON object.

Sign up to request clarification or add additional context in comments.

3 Comments

jQuery.parseJSON() has been deprecated.
@MarcL. What should replace it?
@Parapluie JSON.parse has been part of the "standard built-in" objects for several years now.
41

As simple as that.

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

2 Comments

As the comment on the original question states, the string as given is not valid JSON.
In some cases (like mine) you might find a trailing comma at the end of the string causes some issues. This method will still work - you just need to remove that last comma using regex first: str = str.replace(/,\s*$/, "");
33

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..

2 Comments

“eval is Evil: The eval function is the most misused feature of JavaScript. Avoid it” - Douglas Crockford in "Javascript: The Good Parts" Eval is not recommended due to how dangerous it can be. It's better to use JSON.parse() instead.
Thanks a ton after lots of research I ended up with eval function!! which transformed my stringed JSON to actual array type JSON data
7

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.

Comments

5

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

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.