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
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.
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.
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.
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.
Using jQuery:
var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
var jsonObj = $.parseJSON('[' + str + ']');
jsonObj
is your JSON object.
As simple as that.
var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
dataObj = JSON.parse(str);
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With