2011-09-07 100 views
0

谁能帮我不能为我的生命明白为什么我不能让下面的工作,我只是试图检索从以下JSON值:阅读JSON值问题

{ 
"entities": [ 
    { 
     "id": "84", 
     "name": "jonathan", 
     "date": "2009-12-12", 
     "startTime": "T16:31:04", 
     "endTime": "T16:31:04", 
     "room": "Room1" 
    }, 
    { 
     "id": "87", 
     "name": "jonathan", 
     "date": "2011-12-12", 
     "startTime": "T16:44:03", 
     "endTime": "T16:44:03", 
     "room": "Room1" 
    }, 
    { 
     "id": "90", 
     "name": "jonathan", 
     "date": "2011-12-12", 
     "startTime": "T10:18:38", 
     "endTime": "T10:18:38", 
     "room": "Room1" 
    } 
] 
} 

我有这个做了上千次,但无法访问任何价值,一直在尝试各种变化如下:

console.log(data.entities[0].id); 

请注意我从一个Dojo Ajax调用我能够在整个输出检索JSON JSON到console,所以这不是错误。

当然,我正在做一些愚蠢的学校男孩错误帮助!

+0

在该代码没有错误。 'console.log(data.entities [0]);','console.log(data.entities);'和'console.log(data);'会给你什么? – Znarkus

+0

你正在收到错误?你确定它不是在DOJO中被看作是一个字符串,而不是一个JSON对象吗? – epascarello

+1

这是有效的JSON,也许你需要解析它。 'JSON.parse(data).entities [0] .id' – Joe

回答

0

这似乎为我工作确定:http://jsfiddle.net/77W58/

它必须与data变量的一个问题。它绝对叫data?它是否在范围内?它是一个字符串而不是JSON?真的很明显,但有时候这是最简单的事情。

+0

谢谢尼克是数据绝对存在,我要调查代码的其他部分作为JSON等看起来不错。干杯 – jonnyhitek

0

你的ajax请求是什么样的?如果您没有属性handleAs:'json',则回复将以文本形式返回。在这种情况下,如果您使用console.log响应,您将看到响应,但不会将其输入为对象。

dojo.xhrPost({ 
    url: '/something', 
    handleAs: 'json', 
    load: function(data){ 
    //this should show up as an Object in the console 
    console.log(data); 
    } 

}); 

Vs的

dojo.xhrPost({ 
    url: '/something', 
    //optional, defaults to this property 
    handleAs: 'text', 
    load: function(data){ 
    //this should show up as a string in the console 
    console.log(data); 
    } 

});