Wikipedia API query response is [object Object]. Why?

Wikipedia API query response is [object Object]. Why?
0.0 0

#1

After dealing with styling issues, wrapping my mind around querying Wikipedia’s API, and overcoming the dreaded CORS error… I’ve reached yet another stumbling block.

Regardless of what I put into the field of my , my code displays [object Object] on the page where I want it to display properties of the JSON object I queried for. When I go to my Dev Tools in Chrome and check out the Network, it looks like the query is executing according to the user’s input. And it looks like it’s receiving a JSON object in response. But on the page, I just see [object Object]. When I try to access any of the object’s properties (e.g. json.query.pages[0].title), I get the following error: “Uncaught TypeError: Cannot read property ‘title’ of undefined.”

I’m not sure what I’m missing here, and I would really appreciate some help. Here’s my pen:


#2

Because you are trying to render an object. json.query.pages[0].title does not exist. Try Object.values(json.query.pages)[0].title


#3

I will try that. But why do I have to access the object’s properties this way? I completed the random quote machine challenge by manipulating the JSON object in the way I have initially tried in this challenge (e.g. something like json.quote.author returned the author’s name).


#4

Print json.query.pages to your console and look at it for yourself. This is not outputting an array of objects with ‘title’ as a key, it is outputting an array of objects that have the wikipedia page id as keys. This is just the way the API outputs data and it may be completely different than another API like your random quote generator.

I should also note that Object.values is not ES5 and may not be supported by some browsers (explorer) so you may want to use babel or something like this to access your results:

    Object.keys(json.query.pages).map(function(key) {
      return json.query.pages[key];
    });

#5

So, I don’t understand why I can’t access the JSON object’s properties with bracket notation. I can console.log(Object.values(json['query']['pages'], but if I try to console.log(Object.values(json['query']['pages'][0] I get an error. What’s the problem? Shouldn’t I be able to access the [0] index using bracket notation?