JavaScript loop through JSON array? JavaScript loop through JSON array? json json

JavaScript loop through JSON array?


Your JSON should look like this:

var json = [{    "id" : "1",     "msg"   : "hi",    "tid" : "2013-05-05 23:35",    "fromWho": "hello1@email.se"},{    "id" : "2",     "msg"   : "there",    "tid" : "2013-05-05 23:45",    "fromWho": "hello2@email.se"}];

You can loop over the Array like this:

for(var i = 0; i < json.length; i++) {    var obj = json[i];    console.log(obj.id);}

Or like this (suggested from Eric) be careful with IE support

json.forEach(function(obj) { console.log(obj.id); });


There's a few problems in your code, first your json must look like :

var json = [{"id" : "1", "msg"   : "hi","tid" : "2013-05-05 23:35","fromWho": "hello1@email.se"},{"id" : "2", "msg"   : "there","tid" : "2013-05-05 23:45","fromWho": "hello2@email.se"}];

Next, you can iterate like this :

for (var key in json) {if (json.hasOwnProperty(key)) {  alert(json[key].id);  alert(json[key].msg);}}

And it gives perfect result.

See the fiddle here : http://jsfiddle.net/zrSmp/


try this

var json = [{    "id" : "1",     "msg"   : "hi",    "tid" : "2013-05-05 23:35",    "fromWho": "hello1@email.se"},{    "id" : "2",     "msg"   : "there",    "tid" : "2013-05-05 23:45",    "fromWho": "hello2@email.se"}];json.forEach((item) => {  console.log('ID: ' + item.id);  console.log('MSG: ' + item.msg);  console.log('TID: ' + item.tid);  console.log('FROMWHO: ' + item.fromWho);});