Convert JSON string to array of JSON objects in Javascript

前端 未结 6 1696
感情败类
感情败类 2020-11-27 12:14

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

6条回答
  •  甜味超标
    2020-11-27 12:48

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

提交回复
热议问题