Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert a JSON string to arrays in Javacript

I need a simple help with this question, I’m trying to convert a JSON string to two arrays, look the example:

// What I have
var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}'; 


// What I need:
var array1 = {"id":1,"name":"Test1"};
var array2 = {"id":2,"name":"Test2"};

I tried to do it using JSON.parse(str), but with no success like below:

//Works:

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

//Doesn't work:

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

Any suggestion ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

all you want to do is put the objects in array

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

then:

var array1 = dataObj[0];
var array2 = dataObj[1];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading