在此示例中访问JSON数据时出现问题

时间:2011-01-30 06:19:15

标签: javascript json

这是我有的json,是有效的,但出于某种原因,如果我访问这个query.pages.length是“未定义的”......我怎么知道pages的孩子的数量呢?他们是孩子吗?

  {
       "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"
             }
          }
       }
    }

3 个答案:

答案 0 :(得分:0)

我写了这段代码来计算pages的长度:

count = 0;
for (var key in netData.query.pages) {
count = count + 1;
}
alert(count);

答案 1 :(得分:0)

query.pages是一个对象,而不是一个数组。如果您可以控制生成json,则可以将其设为一个对象数组:

"query":{
  "pages":[
    {
      "pageid":174059,
      "ns":0,
      "title":"Tron"
    },
    {
      "pageid":29799461,
      "ns":0,
      "title":"Tron: Betrayal"
    },
    {
      "pageid":2424602,
      "ns":0,
      "title":"Tron: Deadly Discs"
    }
  ]
}

然后你可以使用query.pages.length。使用数组很好,因为键只是pageid。

答案 2 :(得分:0)

我必须处理这个......你需要遍历页面中的每个页面,并检查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
}

我之前见过这种邋j的json,工程师应该被枪杀。