Alex Rivera | Logout

How to loop through an JSON associative array in javascript?

Asked 2011-05-18T15:47:35.913
12

I'm getting a JSON response from the server and i have to loop through the array in javascript and get the values. But I cant seem to loop throught it.

The JSON response of the array looks like this:

{
   "1": "Schools",
   "20": "Profiles",
   "31": "Statistics",
   "44": "Messages",
   "50": "Contacts"
}

I just want to loop through it to get the ID and Name and populate some values on the page.

I have tried:

$.each(response, function(key, value) {
    alert(key + ' ' + value);
});

// and 

for (var key in response) {
    alert(key + ' ' + response[key]);
}

But neither give the right values.

Thanks in advance for any help.

Reply: Hi, The response I'm getting with the second loop is:

0 {
1 "
2 1
3 "
4 :
5 "
6 S

etc etc

So that means its going through the whole response as a string and spliting it as key/value.

Thanks

Edit
Report

1 Answer

0

Consider looking at How can I parse a JavaScript object with jQuery for a possible answer.

answered 2011-05-18T15:49:05.010

Your Answer