Niranjan Sonachalam
Niranjan Sonachalam

Reputation: 1625

Accessing JSON value without knowing the key

I have a json structure as shown in the imageJSON. I want to fetch the extract value. Normally I would do

         $.ajax({
        type: 'GET',
        url: 'test2.php',
        dataType: "json",
        cache: false,
        success: function(result) 
        {     
            console.log(result.query.pages[168387].extract);

        }
    });

But the value 168387 is not a constant and is going to change for each request. Can you please tell me how to access the value of EXTRACT in this case?

Upvotes: 0

Views: 612

Answers (2)

tymeJV
tymeJV

Reputation: 104775

You'll have to loop and check:

for (var key in result.query.pages) {
    if (result.query.page[key].hasOwnProperty("extract"))
        console.log(result.query.page[key].extract); //or log the key value
}

Upvotes: 4

Rob Baillie
Rob Baillie

Reputation: 3460

Many many options:

If you know the value of the field, and have it in a variable then can't you just change:

console.log(result.query.pages[168387].extract

To

console.log(result.query.pages[variableWithTheAttributeNameInIt].extract

If the "Pages" object is actually an array with consistently shaped objects in it, then make it such and let it auto-increment a key for you. Then it will be natural to loop over it as the array it is.

If it's not a consistent array and you don't have access to any source that will tell you what the attribute name is, then:

  • Change the object so that it tells you itself (e.g. add a new field that IS consistent that tells you what the name of the attribute is)
  • Change the object so that the attribute name doesn't change.

With a preference for the second option over the first.

Upvotes: 0

Related Questions