I’m a javascript noob so this might be a dumb question. I’m trying to get data from the wikipedia api (specifically, the url of the main image of the article), but it’s nestled in a bunch of layers, like this:
{
"batchcomplete": "",
"query": {
"normalized": [
{
"from": "tortilla",
"to": "Tortilla"
}
],
"pages": {
"51418585": {
"pageid": 51418585,
"thumbnail": {
"source": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/ef/Mexican_tortilla.jpg/300px-Mexican_tortilla.jpg",
"width": 300,
"height": 200
},
"pageimage": "Mexican_tortilla.jpg"
}
}
}
}
The page id (51418585 in this case) is dynamic, and there’s no way of knowing it beforehand as far as I know. My question is, how can I get the value of "source" without knowing what "51418585" is?
This is my code:
getJSON(url, function(err, data) {
if (err !== null) {
alert('Something went wrong: ' + err);
} else {
console.log(data[2][0].thumbnail.source);
}
});
I just want to be able to log the "source" url to the console.
Thanks.
>Solution :
Using the answer in this post: get keys of json-object in JavaScript
You can run Object.keys on the JSON object you retrieve and get to the source like this:
getJSON(url, function(err, data) {
if (err !== null) {
alert('Something went wrong: ' + err);
} else {
temp = Object.keys(data.query.pages);
console.log(data.query.pages[temp[0]].thumbnail.source);
}
});