如何访问Wikipedia API返回的JSON中的嵌套对象 [英] How to access nested object in JSON returned by Wikipedia API

查看:99
本文介绍了如何访问Wikipedia API返回的JSON中的嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从此查询到Wikipedia API:

From this query to the Wikipedia API:

http://en.wikipedia.org/w/api.php?action=query&prop=links&format=json&plnamespace=0& pllimit=10&titles=List%20of%20television%20programs%20by%20name

我得到一个JSON结构,例如:

I get a JSON structure, e.g.:

var data = {
  "query": {
    "pages": {
      "1536715": {
        "pageid": 1536715,
        "ns": 0,
        "title": "List of television programs by name",
        "links": [
          {
            "ns": 0,
            "title": "$1.98 Beauty Show"
          },
          {
            "ns": 0,
            "title": "''Dance Academy''"
          }
        ]
      }
    }
  },
  "query-continue": {
    "links": {
      "plcontinue": "1536715|0|15\/Love"
    }
  }
}

我想使用"links"数组的元素.但是,基于元素"pageid": 1536715的存在,我怀疑嵌套对象"1536715"的名称是可以更改的动态值.我不愿意使用此名称来访问链接"数组,例如query.pages.1536715.links.

I want to work with the elements of the "links" array. However, based on the existence of the element "pageid": 1536715, I suspect the name of the nested object "1536715" is a dynamic value that may change. I am reluctant to use this name to access the "links" array, e.g. query.pages.1536715.links.

是否有任何方法(例如,使用通配符query.pages.*.links)越过"该对象?如果失败,我可以迭代pages的子级来获取此对象吗?我正在为此项目使用jQuery 1.7.2,以防您可以从那里建议任何有用的方法.

Is there any way to "step" past this object, i.e. with a wild card query.pages.*.links? Failing that, can I iterate the children of pages to get this object? I am using jQuery 1.7.2 for this project, in case you can suggest any helpful methods from there.

推荐答案

是的,您需要对其进行循环.另请参见非常相似的问题使用jQuery从Wikimedia解析json字符串.您还可以使用 indexpageids参数接收结果页面ID的列表.

Yes, you will need to loop over it. See also the very similiar question parse json string from wikimedia using jquery. You could also receive a list of result pageids using the indexpageids parameter.

if (data && data.query && data.query.pages)
    var pages = data.query.pages;
else
    // error: No pages returned / other problems!
for (var id in pages) { // in your case a loop over one property
    var links = pages[id].links
    if (links)
        for (i=0; i<links.length; i++) {
            // do what you want with links[i]
        }
    else
        // error: No links array returned for whatever reasons!
}

这篇关于如何访问Wikipedia API返回的JSON中的嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆