2011-09-07 140 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); 
    } 

});