2016-08-17 218 views
0

我想從JSON對象訪問某個值。我嘗試訪問的值是從具有大量嵌套對象和數組的JSON對象啓動 - > rocket-> agencies-> abbrev。出於某種原因,我無法訪問某個嵌套級別以下的值。以下是控制檯中記錄的JSON對象的屏幕截圖。訪問嵌套的JSON值

JSON Object screenshot http://prntscr.com/c6ym11 編輯:Link to the image, since embedding didn't work

Here is a link to an example of the JSON formatting in the returned data

這些都是我已經試過的方法:

data = JSON.parse(data); 
var agency = []; 
var names = []; 
var configuration = []; 

for(i = 0; i < data.launches.length; i++){ 
    //This works just fine 
    names.push(data.launches[i].name); 

    //This also works 
    configuration.push(data.launches[i].rocket.configuration); 

    //This returns undefined 
    agency.push(data.launches[i].rocket.agencies.abbrev); 

    //This generates Uncaught TypeError: Cannot read property 'abbrev' of undefined 
    agency.push(data.launches[i].rocket.agencies[0].abbrev); 
} 

我可以訪問關鍵:在 「火箭」 的水平值對,但我不能訪問嵌套在該級別以下的任何東西。我如何調用數據有什麼問題嗎?

+0

你的榜樣它會工作。所以你最有可能擁有json的一部分,你沒有顯示哪裏代理不在[0]。 https://jsfiddle.net/8oeu7qsm/ – baao

回答

2

從json對象的結構看來,您需要索引關閉機構。代碼示例的最後一行應該可以工作。

我可以想象你會希望像

for(j = 0; j < data.launches[i].rocket.agencies.length; j++){ 
    agency.push(data.launches[i].rocket.agencies[j].abbrev); 
} 

這樣,如果沒有機構的,你不會得到錯誤

+0

謝謝。語法有點不合適,但是我可以調整它以使其工作!有道理,我需要另一個循環來確定機構對象的索引。 – ncox85

+0

沒問題!很高興我能幫上忙! –

0

這是什麼工作:

for(i = 0; i < data.launches.length; i++){ 
    for(j = 0; j < data.launches[i].rocket.agencies.length; j++){ 
    company.push(data.launches[i].rocket.agencies[j].abbrev); 
    }; 
}