CyberJunkie CyberJunkie - 1 month ago 6
jQuery Question

jQuery Ajax: get specific object value

I'm accessing a dictionary REST API using Ajax.

$.ajax({
url: "http://api.wordnik.com//v4/word.json/cat/definitions?api_key=mykey&includeRelated=false&includeTags=false&limit=1",
dataType : 'json',
success: function(data) {
//called when successful
alert(data.word);
},
error: function(e) {
//called when there is an error
console.log(e.message);
}
});


The response:

[
{
"textProns": [],
"sourceDictionary": "ahd-legacy",
"exampleUses": [],
"relatedWords": [],
"labels": [],
"citations": [],
"word": "cat",
"text": "A small carnivorous mammal (Felis catus or F. domesticus) domesticated since early times as a catcher of rats and mice and as a pet and existing in several distinctive breeds and varieties.",
"sequence": "0",
"score": 0.0,
"partOfSpeech": "noun",
"attributionText": "from The American Heritage® Dictionary of the English Language, 4th Edition"
}
]


In my test example I get an alert
undefined
on success. Most Ajax examples I saw use loops but I'm returning one result. How can I extract the
word
and
text
values from the objects?

dda dda
Answer

As you can see your response starts with [ and ends with ]. So your response is an array. Then, inside the array, you get objects (starting with { and ending with }). So your data is an array, which can be accessed with data[x] (x being the index), and each member of the selected object can be accessed with the .dot notation: .word, .text etc. So in your case, if there's only one result, you can do data[0].word.