James Wilson
James Wilson

Reputation: 5150

Trying to loop through Json

$('#myClick2').change(function () {
   if (this.checked) {
     $.getJSON('message_center_getMessageLists.asp', {}, function (json) {

             $.each(json.items, function (i, item) {
              alert(item.rank.distID);
              alert(item.rank.name);
              alert(item.rank.description);
             });
         })
         .error(function () {
           alert("There was an error while trying to make this request;  If it persists please contact support"); 
   });
  }
});

I cannot seem to get the above to work, I have to be missing something.

Below is the Json I am trying to loop through

{
    "rank": [
        {
            "distID": "1",
            "name": "John Doe",
            "description": "My Rank"
        },
        {
            "distID": "2",
            "name": "Jane Dow",
            "description": "My Rank"
        },
        {
            "distID": "3",
            "name": "Robin Doe",
            "description": "My Rank"
        },
        {
            "distID": "4",
            "name": "Ryan Doe",
            "description": "My Rank"
        }
    ]
}

Upvotes: 0

Views: 134

Answers (3)

jfriend00
jfriend00

Reputation: 708026

If that's your JSON response, you need this:

$.each(json.rank, function (i, item) {
    alert(item.distID);
    alert(item.name);
    alert(item.description);
});

This is because your JSON is an object with one property named rank and that property contains an array of objects that are what you want to iterate over. So you pass json.rank to $.each() and you will get each object in the array as item.

Adding some line breaks so you can see it better, this is your JSON response:

{
    "rank": [
        {"distID":"1","name":"John Doe","description":"My Rank"},
        {"distID":"2","name":"Jane Dow","description":"My Rank"},
        {"distID":"3","name":"Robin Doe","description":"My Rank"},
        {"distID":"4","name":"Ryan Doe","description":"My Rank"}
    ]
}

So if that was set equal to your success argument json, you can see how the array would be json.rank. And, then you'd access each items properties inside the .each() loop with item.distId, item.description, etc...

Upvotes: 2

Alexander Corwin
Alexander Corwin

Reputation: 1167

well, item.rank doesnt make any sense. The value of rank is an array of JSON objects. What you actually want is to loop over the elements of rank. This syntax will be iffy but

$.each(json.items.rank (i, item) {
  alert(distId);
});

Upvotes: -1

orolo
orolo

Reputation: 3951

it looks like you might want:

$.each(json.rank, function(i, item)

?

Upvotes: 3

Related Questions