Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get a value from json data without knowing the key name?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
  }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading