Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wikipedia API - Accessing JSON Object

I'm trying to pull the text out of a Wikipedia article using their API (API is a generous term for what they are offering, but we'll use it I guess), and I am running into issues regarding parsing of the subsequent JSON object I am getting back. Namely, the object contains the text I am looking for under a key whose label is '*' such that, after running the command:

$.getJSON("http://en.wikipedia.org/w/api.php?action=parse&format=json&callback=?", {page:"Red Sea clownfish", prop:"text"}, function(data) {

I then attempt to parse this information into a string using the command:

var dat = data.parse.text.*;

Which I am then outputting to a console using:

console.log(dat);

Unfortunately, neither Google Chrome nor Firefox seem to be able to parse the '*' key. When I dump the full 'data' object into the console, I can see that the (nested) keys for the data structure are 'parse', 'text', and '*'. I can even dump the text I need up to the '*' key. I.e.

var dat = data.parse.text;

works. It's just that '*' character does not want to be recognized.

Any ideas on how to fix this? Ideally I'd like to get access to the value that the '*' key is referencing. I just have no idea how to program it in javascript.

like image 310
Mephistopheles Avatar asked Nov 14 '11 16:11

Mephistopheles


1 Answers

The * character isn't allowed as part of an identifier (variable name) in JavaScript, so that syntax doesn't work. Instead, you can use the array/subscript notation to access properties using any string, regardless of whether it's a valid identifier:

var dat = data.parse.text['*'];
like image 166
Jeremy Avatar answered Sep 28 '22 08:09

Jeremy