从json对象访问值

时间:2015-06-09 13:44:53

标签: javascript ajax json

ajax调用返回一个像这样的json对象:

Object {0: "1", 1: "jake", 2: "#00ff00", tip_id: "1", tip_details: "jake", tip_color: "#00ff00"}

Object {0: "2", 1: "jakee", 2: "#00ff00", tip_id: "2", tip_details: "jakee", tip_color: "#00ff00"}

Object {0: "3", 1: "jakeee", 2: "#00ff00", tip_id: "3", tip_details: "jakeee", tip_color: "#00ff00"}

这是我尝试访问某些值的方法:

for(var i=0;i<=response.length-1;i++){
  console.log(response[i][1]);  //the result should be: jake,jakee,jakee
}

我也尝试过:

for(var i=0;i<=response.length-1;i++){
      console.log(response[i].tip_details);  //the result should be: jake,jakee,jakee
}

我无法得到它们,我不知道为什么,我错过了什么?

2 个答案:

答案 0 :(得分:1)

这不是JSON对象。 JSON表示法只允许键是字符串而不是数字。

考虑查看类似问题here的答案。

答案 1 :(得分:0)

那些不是JSON。那些是JS对象。 JSON键只有字符串。

使用response检查console.log(response)中的内容。考虑到response是javascript对象数组,下面的代码应该返回预期的输出。

for(var i=0; i<=response.length-1; i++){
  console.log(response[i][1]);
}