Skip to content
Advertisement

String to array object in javascript

I have a string like this:

var x = "[{"id": "40", "text": "Budi "}, {"id": "47", "text": "Staff 01"}]"

I expect to loop until end and read the id and text one by one, how to do this in javascript?

I have tried below:

var myArr = JSON.parse(x);
for (var i in myArr) {
     alert(myArr[i]);
}

Advertisement

Answer

Your JavaScript is invalid. Make sure to wrap it in single quotes.

var x = '[{"id": "40", "text": "Budi "}, {"id": "47", "text": "Staff 01"}]'
var myArr = JSON.parse(x);
for (var i in myArr) {
     console.log("id: " + myArr[i].id);
     console.log("text: " + myArr[i].text);
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement