JSON动态Javascript解析”;未定义”;

JSON Dynamic Javascript parsing "undefined"

本文关键字:未定义 解析 动态 Javascript JSON      更新时间:2023-10-07

一个简单的问题:

暗示变量r类似于:

{
"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"
}
]
}

作为一个JSON字符串,我使用常规的JSON.parse方法:

var parsedJSONquery =JSON.parse(r);

为什么它在控制台中显示,当我简单地尝试调用console.log(parsedJSONquery.definitions.text)时,它会返回"未定义",为什么它不登录到控制台"互联网搜索,比如在谷歌搜索引擎上执行的搜索"?

建议之后:谢谢你的帮助,但我真正想做的是用Ajax从php文件中调用一些JSON(作为变量r),我认为这与我在这里要求的没有什么不同,但是,当我从php文件动态调用JSON时,当我尝试在动态调用的变量r上使用您的任何一个答案时,它会给我一个错误(我不知道本地变量和$.ajax({ url:"url",function(r){ var parsedJSONquery=JSON.parse(r); console.log(parsedJSONquery.definitions[0].text); }})的响应变量之间应该有什么区别?)?!?!这是对象错误吗?

因为undefined-definitions实际上是一个数组。要获得您期望的问题输出-

console.log(parsedJSONquery.definitions[0].text); 

您可以使用常用的Array函数来处理它——例如,在所有这些函数上调用console.log——

obj.definitions.forEach(function(el) { 
  console.log(el.text); 
});