[英]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? 这是我拥有的json,是有效的,但是由于某种原因,如果我访问此
query.pages.length
为“未定义” ...我怎么知道pages
子元素的numebr呢? 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
: 我写了这段代码来计算
pages
长度:
count = 0;
for (var key in netData.query.pages) {
count = count + 1;
}
alert(count);
query.pages is an object, not an array. query.pages是一个对象,而不是数组。 If you are in control of generating the json, you can make it an array of objects instead:
如果您可以控制生成json,则可以将其设置为对象数组:
"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. 那么您可以使用query.pages.length。 using an array is fine, since the key is just the pageid.
使用数组很好,因为键只是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... 我不得不处理这个问题...您需要遍历页面中的每个页面,并检查hasOwnProperty,或者是否都已编号...
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. 我以前见过这种草率的json,应该给工程师开枪。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.