parse json string from wikimedia using jquery

后端 未结 1 398
无人共我
无人共我 2020-12-20 01:03

Im tring to get the infobox from wiki pages. For this I\'m using wiki api. The following is the url from which I\'m getting json data.

http://en.wikipedia.org/w/api.

相关标签:
1条回答
  • 2020-12-20 01:28

    If you want the actual html as it is displayed in the wikipage, use action=parse instead. And yes, the result objects are deeply nested. But no reason to loop over them!

    • the first property is always the action, here: query
    • you have requested properties of pages, so you will receive pages
    • which are keyed by their page id. This is the only step to use a loop
    • Each page object has certain properties (like a title), you're interested in the revisions
    • this is an array of revision objects, you need the only and first
    • the sourcetext property of a revision object is the *

    So, just do it:

    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
        if (pages[id].revisions && pages[id].revisions[0] && pages[id].revisions[0]["*"])
            var content = pages[id].revisions[0]["*"];
        else
            // error: No revision content returned for whatever reasons!
    }
    // use "content" variable here
    

    Dont forget to check for the existance of each object! If you requested no pages, there will be no pages object; this is only the case when the pages "array" is empty. A page may be missing/invalid title or something else, so that is has no revisions. etc.

    0 讨论(0)
提交回复
热议问题