Javascript how to parse JSON array
Javascript has a built in JSON parse for strings, which I think is what you have:
var myObject = JSON.parse("my json string");
to use this with your example would be:
var jsonData = JSON.parse(myMessage);for (var i = 0; i < jsonData.counters.length; i++) { var counter = jsonData.counters[i]; console.log(counter.counter_name);}
EDIT: There is a mistake in your use of for loop (I missed this on my first read, credit to @Evert for the spot). using a for-in loop will set the var to be the property name of the current loop, not the actual data. See my updated loop above for correct usage
IMPORTANT: the JSON.parse
method wont work in old old browsers - so if you plan to make your website available through some sort of time bending internet connection, this could be a problem! If you really are interested though, here is a support chart (which ticks all my boxes).
This is my answer:
<!DOCTYPE html><html> <body> <h2>Create Object from JSON String</h2> <p> First Name: <span id="fname"></span><br> Last Name: <span id="lname"></span><br> </p> <script> var txt = '{"employees":[' + '{"firstName":"John","lastName":"Doe" },' + '{"firstName":"Anna","lastName":"Smith" },' + '{"firstName":"Peter","lastName":"Jones" }]}'; //var jsonData = eval ("(" + txt + ")"); var jsonData = JSON.parse(txt); for (var i = 0; i < jsonData.employees.length; i++) { var counter = jsonData.employees[i]; //console.log(counter.counter_name); alert(counter.firstName); } </script> </body></html>
In a for-in-loop the running variable holds the property name, not the property value.
for (var counter in jsonData.counters) { console.log(jsonData.counters[counter].counter_name);}
But as counters is an Array, you have to use a normal for-loop:
for (var i=0; i<jsonData.counters.length; i++) { var counter = jsonData.counters[i]; console.log(counter.counter_name);}