Question

I’m requesting JSON from Wikipedia’s API at

http://en.wikipedia.org/w/api.php?action=query&prop=description&titles=WTO&prop=extracts&exsentences&explaintext&format=json

The response looks like this:

{
    "query": {
        "pages": {
            "ramdom_number_here": {
                "pageid": ramdom_number_here,
                "ns": 0,
                "title": "Hello",
                "extract": "Hello world! Enchanté to meet you"
            }
        }
    }
}

Given that ramdom_number_here changes each request (so we don't know it), how can extrac or title’s data be accessed?

Was it helpful?

Solution

Use Object.keys(data)[x] to replace the nominative pathway byt the the coordinate of your data.

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

Solution> JSfiddle:

function WD(val) { // input
    target_API_url = "http://zh.wikipedia.org/w/api.php?action=query&prop=description&titles=" + val.toString() + "&prop=extracts&exintro&explaintext&format=json&redirects&callback=?";
    $.getJSON(target_API_url, function (json) {
        trad = json.query.redirects[0].to; // no "var", variable is global
        var item_id = Object.keys(json.query.pages)[0]; // THIS DO THE TRICK !
        sent = JSON.stringify(json.query.pages[item_id].extract);
        result = "<b>En:</b> "+val.toString() + ", <b>Zh: </b>"+trad.toString() +  "<br /><b>⇒</b>" + sent.toString();
        $('p').html(result); // transformation 
    });
};
WD("WTO");

Encouraging +1 welcome.

OTHER TIPS

In javascript you can:

var a; // assume that a is your json
var title;
for (var obj in a["query"]["pages"])
{
  if (a["query"]["pages"][obj].title != undefined)
  {
   title = a["query"]["pages"][obj].title;
   break;
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top