Reputation: 1625
I have a json structure as shown in the image. 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
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
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:
With a preference for the second option over the first.
Upvotes: 0