I'm doing a project with the wikipedia media API. I'm querying the API using Jquery. The following request works when checking the developper console in Chrome as seen in this codepen http://codepen.io/jowze/pen/NNZNKY/?editors=1010
$.ajax({
url:'https://en.wikipedia.org/w/api.php',
data: { action : 'query', generator: 'search', gsrnamespace : '0', gsrlimit : '10', prop : 'extracts', pilimit: 'max',
exintro: '', explaintext: '', exsentences: '1' , exlimit: 'max' , gsrsearch: 'Richard Feynman', format: 'json'},
dataType: 'jsonp',
success: function (x) {
var result = x.query.pages;
for (var i in result) {
var item = result[i].pageid;
console.log(item);
}
}
});
This code works when looping through the result with a for...in loop. When writing the same code trying to access the result variable like below, the console prints an Uncaught TypeError: Cannot read property 'pageid' of undefined
success: function (x) {
var result = x.query.pages;
var item = result[0].pageid;
console.log(item);
}
});
Any idea why this is happening? Why is it impossible to access each key of the JSON object via result[0]
, result[1]
,... ,result[n]
?