Javascript 无法访问JSON对象
我无法访问我的JSON对象Javascript 无法访问JSON对象,javascript,json,Javascript,Json,我无法访问我的JSON对象 // test.json { "greet": [ "hi" ] } 首先,我返回JSON对象,其中包含: console.log(JSON.parse(this.responseText)); 它返回正确的JSON对象 // test.json { "greet": [ "hi" ] } 但当我想通过以下方式访问对象时: console.log(JSON.parse(this.responseT
// test.json
{
"greet": [
"hi"
]
}
首先,我返回JSON对象,其中包含:
console.log(JSON.parse(this.responseText));
它返回正确的JSON对象
// test.json
{
"greet": [
"hi"
]
}
但当我想通过以下方式访问对象时:
console.log(JSON.parse(this.responseText["greet"]));
它返回:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
为什么?你应该做:
let parsedJson = JSON.parse(this.responseText)
console.log(parsedJson["greet"])
因为this.responseText
是一个字符串,您必须首先使用JSON.parse()
将其转换为对象
希望这会有所帮助。这个
[“greet”]
在JSON.parse()
的关闭之后进行。@zero298说的是console.log(JSON.parse(this.responseText)[“greet”]代码>打印“hi”没有JSON对象这样的东西。JSON总是一个字符串。