Reputation: 112
Implying that variable r is something like:
{
"definitions":[
{
"text":"An internet search, such as that which is performed on the Google search engine.",
"attribution":"from Wiktionary, Creative Commons Attribution/Share-Alike License"
},
{
"text":"A match obtained by a query in the Google search engine.",
"attribution":"from Wiktionary, Creative Commons Attribution/Share-Alike License"
},
{
"text":"To search for (something) on the Internet using the Google search engine.",
"attribution":"from Wiktionary, Creative Commons Attribution/Share-Alike License"
},
{
"text":"To search for (something) on the Internet using any comprehensive search engine.",
"attribution":"from Wiktionary, Creative Commons Attribution/Share-Alike License"
},
{
"text":"To be locatable in a search of the Internet.",
"attribution":"from Wiktionary, Creative Commons Attribution/Share-Alike License"
},
{
"text":"To deliver googlies.",
"attribution":"from Wiktionary, Creative Commons Attribution/Share-Alike License"
},
{
"text":"To move as a ball in a googly.",
"attribution":"from Wiktionary, Creative Commons Attribution/Share-Alike License"
}
]
}
Being a JSON string, I use the regular JSON.parse method :
var parsedJSONquery =JSON.parse(r);
Why does it display in the console that when I simply try to call something like console.log(parsedJSONquery.definitions.text), it returns "undefined", why is it not logging to the console "An internet search, such as that which is performed on the Google search engine." for example?
After the suggestions: Thanks for the help, but what I am really trying to do is to call in with Ajax some JSON from a php file (as the variable r), which I thought would be no different from what I asked here, but when I dynamically call in the JSON from the php file it gives me an error (I don't see what the difference should be between the local variable and the response variable from the $.ajax({
url:"url",function(r){
var parsedJSONquery=JSON.parse(r);
console.log(parsedJSONquery.definitions[0].text);
}})
?) when I try to use either of your answers on the dynamically called variable r I get: SyntaxError: JSON Parse error: Unexpected identifier "object"?!?! Is it an object error?
Upvotes: 0
Views: 124
Reputation: 15425
Because it is infact undefined
- definitions
is an Array. To get the output you expect from your question -
console.log(parsedJSONquery.definitions[0].text);
You would use the usual Array functions to work with it - for example, to call console.log on all of them -
obj.definitions.forEach(function(el) {
console.log(el.text);
});
Upvotes: 2