我正在尝试循环一些 JSON,然后将其附加到 DOM。当我解析 JSON 并将其放入元素中时,我得到未定义的返回值。
<div id="myDiv"></div>
let myJSON = '{"games": [{"name ": "game1 "},{"name ": "game2 "},{"name ": "game3 "}]}'
let myDiv = document.querySelector("#myDiv");
let myParsedJSON = JSON.parse(myJSON);
for(let i = 0; i < myParsedJSON.games.length; i++){
let newDiv = document.createElement("div");
newDiv.innerHTML = myParsedJSON.games[i].name;
myDiv.append(newDiv);
}
我尝试更改 JSON 的解析名称和访问权限,但没有任何改变。我也确信这不是 JSON 本身,因为 JSON Crack 正确地呈现了它。
这里的问题是因为您调用了
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);