0

I understand we can use following to process a simple ajax JSON response

function onSuccess(response) {
    console.log("Service call successful with response"+response);
    $.each(response, function (key, value) {
        console.log(key+" "+value);

    }) ;

But, how to process to an array of JSON response like below?

{
   "xyzs":[
      {
         "xyz":{
            "id":"515f08380364db3bbe5a27f1",
            "xyz_id":"320224817603309569"
         }
      },
      {
         "xyz":{
            "id":"5161f9880364db3bbea86595",
            "xyz_id":"321033680736886784"
         }
      }
   ]
}

onSuccess() function doesn't give expected output id and xyz_id in console with above response.

Is there some for loop in javascript which I use in onSuccess() function to get values of id and xyz_id?

Watt
  • 3,118
  • 14
  • 54
  • 85

3 Answers3

4

You can try this instead :

$.each(response.xyzs, function (index, obj) {
   console.log(obj.xyz.id+" "+obj.xyz.xyz_id);
}) ;

Hope this will help !!

Kundan Singh Chouhan
  • 13,952
  • 4
  • 27
  • 32
  • +1 for quick response. But, I don't know what's wrong happening, I get 2 lines of "undefined undefined" in console for the given JSON in question. I still don't get expected value of id and xyz_id – Watt Apr 25 '13 at 18:13
  • @Watt, i missed the **xyz** node, updated my answer. – Kundan Singh Chouhan Apr 25 '13 at 18:20
1

Use this:

var response = {
   "xyzs":[
      {
         "xyz":{
            "id":"515f08380364db3bbe5a27f1",
            "xyz_id":"320224817603309569"
         }
      },
      {
         "xyz":{
            "id":"5161f9880364db3bbea86595",
            "xyz_id":"321033680736886784"
         }
      }
   ]
};

$.each(response.xyzs, function () {
    var cur = this.xyz;
    console.log(cur.id, cur.xyz_id);
});

DEMO: http://jsfiddle.net/abBcW/

Ian
  • 50,146
  • 13
  • 101
  • 111
  • +1. It worked! thanks for code example as well. I wonder why Kundan's solution didn't work, only difference, he didn't use var cur=this.xyz – Watt Apr 25 '13 at 18:18
0

In your case. you are having a json object, and $.each() will apply to a json array.

So you can get JSON array by response.xyzs and can loop through each element of that array.

 $.each(response.xyzs, function (key, value) {
        console.log(key+" "+value);   
    }) ;

Here is more clear JSON array looping example.

var data = [ 
 {"Id": 10004, "PageName": "club"}, 
 {"Id": 10040, "PageName": "qaz"}, 
 {"Id": 10059, "PageName": "jjjjjjj"}
];

$.each(data, function(i, item) {
    alert(data[i].PageName);
});​

$.each(data, function(i, item) {
    alert(item.PageName);
});​
Ankush Jain
  • 1,532
  • 1
  • 15
  • 24