Question

Given the WikipediaAPI, an article's title on the English wikipedia, I have am url providing back a JSON :

var url = "http://en.wikipedia.org/w/api.php?action=query&prop=description&titles=Unicorn&prop=extracts&exsentences=10&explaintext&format=json";

The response looks like this:

{
    "query": {
        "pages": {
            "ramdom_number_here": {
                "pageid": ramdom_number_here,
                "ns": 0,
                "title": "Unicorn",
                "extract": "The unicorn is a legendary animal that has been described since antiquity as a beast with a large, pointed, spiraling horn projecting from its forehead."
            }
        }
    }
}

Given that <ramdom_number_here> changes for each article and is thus unpredictable.

How to grasp the extract or title’s value to reuse it ?

Was it helpful?

Solution

It's mainly the good url to attack the API, a JQuery $.getJSON, and a witty trick to pass the item's id. There, use Object.keys(data)[x] to replace the nominal pathway by the the coordinate of your data with Object.keys(data)[i].

  • Object.keys(data) -- give you the list of keys at that level.
  • Then use i=the numeral rang of your target data. For the first data point, for us [i]=[0].

Solution> JSfiddle:

function WD(item) {
    url = "http://en.wikipedia.org/w/api.php?action=query&prop=description&titles=" + item.toString() + "&prop=extracts&exintro&explaintext&format=json&redirects&callback=?";
    $.getJSON(url, function (json) {
        var item_id = Object.keys(json.query.pages)[0]; // THIS DO THE TRICK !
        sent = json.query.pages[item_id].extract;
        result = "<b>En :</b> <t>" + item + "</t> <b>⇒</b> " + sent;
        $('#anchor1').append("<div>"+result+"</div>"); // transformation 
    });
}
WD("Dragon");

With some expansion, var list = ["dragon", "Unicorn", "Cat"], a wrapping $.each() function, some quick CSS, I get an elegant yet easy result such:

enter image description here

Delete &explaintext if you want html. Dig into the Wikipedia API for more functions.

Encouraging +1 welcome.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top