69

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

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Sobis
  • 1,385
  • 4
  • 20
  • 29
  • 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? – Felix Kling Dec 07 '10 at 10:22

6 Answers6

96

Using jQuery:

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

jsonObj is your JSON object.

darioo
  • 46,442
  • 10
  • 75
  • 103
40

As simple as that.

var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
 dataObj = JSON.parse(str);
Mo.
  • 26,306
  • 36
  • 159
  • 225
Gyanesh Gouraw
  • 1,991
  • 4
  • 23
  • 31
  • 2
    As the comment on the original question states, the string as given is not valid JSON. – Adrian Wragg Mar 10 '14 at 12:44
  • 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*$/, ""); – Sanchez333 Mar 24 '22 at 11:42
32

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

gideon
  • 19,329
  • 11
  • 72
  • 113
AnarchistGeek
  • 3,049
  • 6
  • 32
  • 47
  • 2
    “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. – Jamie Howarth Mar 02 '20 at 18:48
  • Thanks a ton after lots of research I ended up with eval function!! which transformed my stringed JSON to actual array type JSON data – Dipesh Feb 24 '21 at 05:19
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.

Luca Matteis
  • 29,161
  • 19
  • 114
  • 169
5

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

greenimpala
  • 3,777
  • 3
  • 31
  • 39
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.

Steve
  • 29
  • 1