0

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

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"
    }
  }
}

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.

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
psteiner
  • 187
  • 3
  • 17
  • possible duplicate of [parse json string from wikimedia using jquery](http://stackoverflow.com/questions/10196222/parse-json-string-from-wikimedia-using-jquery) – Bergi May 21 '12 at 00:12

2 Answers2

1

This should get you there...

var links, i, pageID;

for (pageID in query.pages) {
    links = query.pages[pageID].links;
    for (i=0; i<links.length; i++) {
        link = links[i];
        link.ns; link.title // handle link obj here.
    }
}
Kenan Banks
  • 207,056
  • 34
  • 155
  • 173
1

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!
}
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375