Json Traverse Problem, not able to traverse values
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": "sh_sup1@shell.com", "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-3开发者_StackOverflow社区1 15:36:53", "created_by": "0", "Id": "82", "fk_location_id": "3874", "address": "THIS is test address", "email": "bp@india.com", "website_url": "http://www.bp.com", "srk_main_id": "0" }, "count": 2 }
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 withmsg = { "1": {...}}
you have a number as property.
Fortunately it is not that bad because you can access this property with "array like" accessmsg["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);
}
精彩评论