在javascript中循环使用JSON数据无法正常工作

时间:2021-07-31 07:25:13

I have some JSON data being returned from an AJAX call. I then need to parse this data in javascript.

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

The data looks like so:

数据看起来像这样:

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

Why is it when i run this code on the data that i get multiple undefined's? (var json being the variable holding my json data)

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

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

     console.log(obj.id);
  }

However if i assign the json directly to the variable like so:

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

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

Then it works fine!

然后它工作正常!

Any ideas guys? Thanks

任何想法的家伙?谢谢

2 个解决方案

#1


1  

Make sure the JSON you're getting is not just stringified JSON. In that case do JSON.parse(json_string) and then loop and more processing.

确保您获得的JSON不仅仅是字符串化的JSON。在那种情况下做JSON.parse(json_string)然后循环和更多处理。

Example:

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

#2


0  

It is not a JSON that, you are using.

您使用的不是JSON。

  • It's an object array.
  • 这是一个对象数组。

  • When you get JSON, parse that JSON using method JSON.parse.
  • 当您获得JSON时,使用方法JSON.parse解析该JSON。

  • Assign this JSON to a variable and then use iteration over it...
  • 将此JSON分配给变量,然后对其使用迭代...

Ex:

 var json ='[{"id": "23","date_created": "2016-05-12 14:52:42"},{"id": "25","date_created": "2016-05-12 14:52:42"}]';
 var parsedJson = JSON.parse(json);
 for(var i = 0; i < parsedJson.length; i++) {
     var obj = parsedJson[i];

     console.log(obj.id);
  }

#1


1  

Make sure the JSON you're getting is not just stringified JSON. In that case do JSON.parse(json_string) and then loop and more processing.

确保您获得的JSON不仅仅是字符串化的JSON。在那种情况下做JSON.parse(json_string)然后循环和更多处理。

Example:

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

#2


0  

It is not a JSON that, you are using.

您使用的不是JSON。

  • It's an object array.
  • 这是一个对象数组。

  • When you get JSON, parse that JSON using method JSON.parse.
  • 当您获得JSON时,使用方法JSON.parse解析该JSON。

  • Assign this JSON to a variable and then use iteration over it...
  • 将此JSON分配给变量,然后对其使用迭代...

Ex:

 var json ='[{"id": "23","date_created": "2016-05-12 14:52:42"},{"id": "25","date_created": "2016-05-12 14:52:42"}]';
 var parsedJson = JSON.parse(json);
 for(var i = 0; i < parsedJson.length; i++) {
     var obj = parsedJson[i];

     console.log(obj.id);
  }