Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON string to array of JSON objects in Javascript

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

like image 781
Sobis Avatar asked Dec 07 '10 10:12

Sobis


People also ask

Can we convert JSON string to array?

Approach 1: First convert the JSON string to the JavaScript object using JSON. Parse() method and then take out the values of the object and push them into the array using push() method.

How do I convert a string to an array in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do you push multiple JSON objects into an array?

Use the Array. push() method to push multiple values to an array, e.g. arr. push('b', 'c', 'd'); . The push() method adds one or more values to the end of an array.

How do you parse an array of JSON objects?

Parsing JSON Data in JavaScript In JavaScript, you can easily parse JSON data received from the web server using the JSON. parse() method. This method parses a JSON string and constructs the JavaScript value or object described by the string. If the given string is not valid JSON, you will get a syntax error.


3 Answers

Using jQuery:

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

jsonObj is your JSON object.

like image 195
darioo Avatar answered Oct 16 '22 15:10

darioo


As simple as that.

var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
 dataObj = JSON.parse(str);
like image 33
Gyanesh Gouraw Avatar answered Oct 16 '22 14:10

Gyanesh Gouraw


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

like image 31
AnarchistGeek Avatar answered Oct 16 '22 15:10

AnarchistGeek