jowze jowze - 6 months ago 19
JSON Question

Uncaught TypeError: Cannot read property 'foo' of undefined

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]
?

Answer

Just put some console logs as mentioned in the below code and you will understand why are you facing this error.

    $.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;
        console.log("== What is the type of result : " + typeof(result)); //Object
        console.log("Complete Result : " + JSON.stringify(result));
        for (var i in result) {
            console.log("Property type for object result :" + typeof(i)); //String
            var item = result[i].pageid;
            var title = result[i].title;
            var extract = result[i].extract;
        }
    }
 });

So, What you are trying to do here is to access the non-numeric object properties by index, which is not possible. If you want to do it, then you can learn more about it here.

Comments