无法访问JSON对象

时间:2019-06-20 19:05:20

标签: javascript json

我无法访问我的JSON对象。

// test.json
{
    "greet": [
        "hi"
    ]
}

首先,我返回JSON对象:

console.log(JSON.parse(this.responseText));

它返回正确的JSON对象。

the JSON object in console in Firefox

但是当我想通过以下方式访问对象greet时:

console.log(JSON.parse(this.responseText["greet"]));

它返回:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

为什么?

1 个答案:

答案 0 :(得分:0)

您应该这样做:

let parsedJson = JSON.parse(this.responseText)

console.log(parsedJson["greet"])

因为this.responseText是一个字符串,您必须首先使用JSON.parse()将其转换为对象。

希望这会有所帮助。

相关问题