gpt4 book ai didi

javascript - 在 JavaScript 中循环 JSON 数据不起作用

转载 作者:行者123 更新时间:2023-11-27 22:59:56 25 4
gpt4 key购买 nike

我有一些从 AJAX 调用返回的 JSON 数据。然后我需要在 JavaScript 中解析这些数据。

数据如下:

[
{
"id": "23",
"date_created": "2016-05-12 14:52:42"
},
{
"id": "25",
"date_created": "2016-05-12 14:52:42"
}
]

为什么当我在数据上运行此代码时会得到多个未定义的?(var json 是保存我的 json 数据的变量)

 for(var i = 0; i < json.length; i++) {
var obj = json[i];

console.log(obj.id);
}

但是,如果我将 json 直接分配给变量,如下所示:

var json = [
{
"id": "23",
"date_created": "2016-05-12 14:52:42"
},
{
"id": "25",
"date_created": "2016-05-12 14:52:42"
}
];

然后就可以正常工作了!

大家有什么想法吗?谢谢

最佳答案

确保您获得的 JSON 不仅仅是字符串化的 JSON。在这种情况下,执行 JSON.parse(json_string) 然后循环并进行更多处理。

示例:

var string_json = '[{"a":1},{"b":2}]'; // may be your API response is like this
var real_json = JSON.parse(string_json); // real_json contains actual objects
console.log(real_json[0].a, real_json[1].b); // logs 1 2

关于javascript - 在 JavaScript 中循环 JSON 数据不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37203181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com