views:

61

answers:

1

I m getting the below return from ajax call but not able to traverse it please please help.

{
    "1": {
        "tel1": null, 
        "status": "1", 
        "fax": "",     
        "tel2": null,  
        "name": "sh_sup1", 
        "country": "Anguilla", 
        "creation_time": "2010-06-02 14:09:40",
        "created_by": "0",
        "Id": "85",
        "fk_location_id": "3893",
        "address": "Noida",
        "email": "[email protected]",
        "website_url": "http://www.noida.in",
        "srk_main_id": "0"
    },
    "0": {
        "tel1": "Ahemdabad",
        "status": "1",
        "fax": "",
        "tel2": "Gujrat",
        "name": "Bharat Petro",
        "country": "India",
        "creation_time": "2010-05-31 15:36:53",
        "created_by": "0",
        "Id": "82",
        "fk_location_id": "3874",
        "address": "THIS is test address",
        "email": "[email protected]",
        "website_url": "http://www.bp.com",
        "srk_main_id": "0"
    },
    "count": 2
}
+2  A: 

You can do it very easily:

for(i = 0; i < msg.count; i++) {
   alert(msg[i]['name']);
} 

But the structure of your JSON object is not that good for several reasons:

  • It does not reflect the structure of the actual data
    With this I mean, that you actually have an array of objects. But in your JSON object the elements of the array are represented as properties of an object.

  • You have invalid JavaScript object property names.
    Properties for objects in JavaScript are not allowed to start with numbers. But with msg = { "1": {...}} you have a number as property.
    Fortunately it is not that bad because you can access this property with "array like" access msg["1"] (instead of the "normal way", msg.1). But I would consider this as bad practice and avoid this as much as possible.


Hence, as Matthew already proposes, it would be better to remove the count entry from the array on the server side, before you sent it to the client. I.e. you should get a JSON array:

[{
     "tel1": "Ahemdabad",
     "status": "1",
     // etc.
 },
 {    
     "tel1": null,
     "status": "1",
     // etc.
 }]

You don't need count as you can get the length of the array with msg.length and you can traverse the array with:

for(var i in msg) {
    alert(msg[i].name);
}
Felix Kling
Thanks to all i managed to get it done , i have changed the complete format of json return and hurrayyy its over.But thanks again for thinking loudly with me for the problem.
Jos
Both JavaScript and JSON objects can have numeric property names. It's not a good idea, but it is valid.
Matthew Flaschen