Problem accessing JSON data on this example
this is a json i have, is valid, but for some reason if I access this query.pages.length
is "undefined"... how do i know the numebr of children of pages
then? are they children?
{
"query-continue":{
"allpages":{
"gapfrom":"Tron (film)"
}
},
"query":{
"pages":{
"174059":{
"pageid":174059,
"ns":0,
"title":"Tron"
},
"29799461":{
"pageid":29799461,
"ns":0,
"title":"Tron: Betrayal"
},
"2424602":{
"pageid":2424602,
"ns":0,
"title":"Tron: Deadly Discs"
},
开发者_如何学运维 "25415189":{
"pageid":25415189,
"ns":0,
"title":"Tron: Evolution"
},
"29958517":{
"pageid":29958517,
"ns":0,
"title":"Tron: Evolution - Battle Grids"
},
"22547607":{
"pageid":22547607,
"ns":0,
"title":"Tron: Legacy"
},
"29541046":{
"pageid":29541046,
"ns":0,
"title":"Tron: Legacy (soundtrack)"
},
"11825742":{
"pageid":11825742,
"ns":0,
"title":"Tron: Solar Sailer"
},
"8005401":{
"pageid":8005401,
"ns":0,
"title":"Tron: The Ghost in the Machine"
},
"29487895":{
"pageid":29487895,
"ns":0,
"title":"Tron: Uprising"
}
}
}
}
I wrote this code to count length of pages
:
count = 0;
for (var key in netData.query.pages) {
count = count + 1;
}
alert(count);
query.pages is an object, not an array. If you are in control of generating the json, you can make it an array of objects instead:
"query":{
"pages":[
{
"pageid":174059,
"ns":0,
"title":"Tron"
},
{
"pageid":29799461,
"ns":0,
"title":"Tron: Betrayal"
},
{
"pageid":2424602,
"ns":0,
"title":"Tron: Deadly Discs"
}
]
}
then you can use query.pages.length. using an array is fine, since the key is just the pageid.
I had to deal with this... you'll need to iterate through each page in pages, and check for hasOwnProperty, or if all are numbered...
var count = 0;
for (var key in query.pages) {
//local page variable
var page = query.pages[key];
//page isn't what you're looking for
if (!page || page.pageid != key) continue;
//increase count
count++;
//do something with page
}
I've seen this kind of sloppy json before, and the engineer should be shot.
精彩评论