I have a string like this:
JavaScript
x
2
1
var x = "[{"id": "40", "text": "Budi "}, {"id": "47", "text": "Staff 01"}]"
2
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:
JavaScript
1
5
1
var myArr = JSON.parse(x);
2
for (var i in myArr) {
3
alert(myArr[i]);
4
}
5
Advertisement
Answer
Your JavaScript is invalid. Make sure to wrap it in single quotes.
JavaScript
1
6
1
var x = '[{"id": "40", "text": "Budi "}, {"id": "47", "text": "Staff 01"}]'
2
var myArr = JSON.parse(x);
3
for (var i in myArr) {
4
console.log("id: " + myArr[i].id);
5
console.log("text: " + myArr[i].text);
6
}