How to loop through an JSON associative array in javascript? How to loop through an JSON associative array in javascript? json json

How to loop through an JSON associative array in javascript?


Your problem is that you are not parsing the JSON string. Therefore, your foreach is going through the characters in the JSON string.

// If you are using jQuery.ajax, you can just set dataType to 'json' // and the following line will be done for youvar obj  = jQuery.parseJSON( response );// Now the two will work$.each(obj, function(key, value) {    alert(key + ' ' + value);});for (var key in obj) {    alert(key + ' ' + response[key]);}


var response = {"1":"Schools","20":"Profiles","31":"Statistics","44":"Messages","50":"Contacts"};for (var i in response) {    console.log(i + ' ' + response[i]);}

Works just fine, how are you getting your response var?


You don't need to do like that, dealing with string is a boring job. You can make a object through the response. 1:json = eval(xmlHttp.responseText);

but this is unsafe in some degree.

  1. json = JSON.parse(xmlHttp.responseText, function(key,value){// can do some other stuff here.});

then you can operate the variable as a normal object like this obj.a or obj["a"].

May this will help you.