解析未知JSON对象的属性

时间:2013-11-24 03:04:52

标签: json mediawiki-api

我正在尝试使用MediaWiki API从维基百科中获取文章。

但是,返回的JSON数据包含pageid作为Object的标识符,但pageid是随机的。

以下是我的代码:

$.getJSON("http://en.wikipedia.org/w/api.php?action=query&generator=random&grnnamespace=0&prop=extracts&exchars=50000&format=json&callback=?", function (data) {
    console.log(data.query.pages);
});

返回的第一页的JSON是这样的:

37889571: Object
    extract: "<p></p>↵<p></p>↵<p><b>Frank A Delaney IV</b>, Born Feb 4, 1963, Denville New Jersey.</p>↵<p>Mr Delaney is the son of Frank A Delaney III, ..."
    ns: 0
    pageid: 37889571
    title: "Frank A Delaney IV"

我想抓取提取或标题console.log(data.query.pages.37889571.extract);等属性,但由于pageid是随机的,我不确定如何达到它。什么是实现这个目标的好方法?

对于那些感兴趣的人,这里是JSON:

{

    "query":{
        "pages":{
            "1302977":{
                "pageid":1302977,
                "ns":0,
                "title":"Russ O'Hara",
                "extract":"<p><b>Russell Eugene Nealeigh O'Hara</b> is a one-time Los Angeles, USA radio personality whose career began at the forefront of the Boss Radio/Top 40 format.</p>\n<p>O'Hara is best known among LA radio listeners for his work on KKDJ<sup class=\"plainlinks noprint Inline-Template\" style=\"vertical-align:text-top;white-space:nowrap;\">[<i>disambiguation needed</i>]</sup> and his longtime solo work on KRLA where he went by the occasional moniker of \"Russ O'Hungry.\" Highly visible among Los Angeles radio personalities, O'Hara had the privilege of introducing headliners at major concerts, including Janis Joplin at the Hollywood Bowl; he also introduced The Rolling Stones, Jimi Hendrix and Three Dog Night among many others.</p>\n<p>He remains active as a broadcaster and currently hosts afternoons on KDES-FM, an oldies station in Palm Springs, California.</p>\n<p>O'Hara worked at the following Los Angeles stations in the course of his career:</p>\n<ul><li>(KBLA), 1964-65.</li>\n<li>KGFJ, 1968-60.</li>\n<li>KRLA, 1969-72.</li>\n<li>KKDJ<sup class=\"plainlinks noprint Inline-Template\" style=\"vertical-align:text-top;white-space:nowrap;\">[<i>disambiguation needed</i>]</sup>, 1972-74.</li>\n<li>KEZY (Anaheim) 1975-77.</li>\n<li>KROQ-FM, 1978-79.</li>\n<li>Return to KRLA, 1981\u201382; 1992-93.</li>\n<li>KEZN Palm Desert 1993-2001.</li>\n</ul><h2>External links</h2>\n<ul><li>KDES webpage</li>\n</ul><p><br></p>"
            }
        }
    }

}

2 个答案:

答案 0 :(得分:1)

我可以使用以下方式访问这些属性:

for(var id in data.query.pages) {
  console.log(data.query.pages[id]);
}

但我不确定这是否是最佳/唯一的方式。

答案 1 :(得分:0)

您现在可以在请求中添加&indexpageids,然后您将获得pageids

例如:
https://en.wikipedia.org/w/api.php?action=query&titles=Leipzig&prop=pageimages&format=json&pithumbsize=1000&indexpageids