如何在 JavaScript 中正确使用
JSON.parse()
?我当前的代码应该访问 games
object
,然后给出游戏对象 name
的输出。为什么我的代码返回 [object Object]
?
let games = '{"games": [{"name": "Funny Game","desc": "A game to make you laugh!"}]}'
JSON.parse(games)
console.log(games[0].name);
//Should output Name
我看过访问没有名称的 json 对象并且也尝试过解决。
这里的问题是因为您调用了
JSON.parse()
,但不对它的输出执行任何操作。您需要将其分配给某个对象,然后询问 that object 以查找 name
属性。这是一个工作示例:
let input = '{"games": [{"name": "PUBG","desc": "Original widely popularised by `The bridge incident.` PUBG is a shooter with many fun modes and distinctive gameplay. "}]}'
const parsedInput = JSON.parse(input)
console.log(parsedInput.games[0].name);
请注意,我更改了变量名称,以避免在保存 JSON 字符串的
games
变量和保存对象数组的 games
属性之间产生混淆。
这是你如何访问它,有一个内部关键“游戏”
let games = '{"games": [{"name": "PUBG","desc": "Original widely popularised by `The bridge incident.` PUBG is a shooter with many fun modes and distinctive gameplay. "}]}'
let parsedJSON = JSON.parse(games)
console.log(parsedJSON.games[0].name);