2017-04-04 184 views
0

我想使用JavaScript讀取JSON文件的嵌套內容。使用JavaScript閱讀嵌套的JSON

這裏是我的JavaScript:

<script> 
var obj, xmlhttp, myObj, x, txt = ""; 
var request = new XMLHttpRequest(); 
request.open('GET', 'https://private-c01be-moneyadviceservice.apiary-mock.com/locale/categories.json'); 
request.setRequestHeader("Content-type", "application/json"); 
request.onreadystatechange = function() { 
if (this.readyState === 4) { 
console.log('Status:', this.status); 
console.log('Headers:', this.getAllResponseHeaders()); 
console.log('Body:', this.responseText); 

    myObj = JSON.parse(this.responseText); 

    for (x in myObj) { 
     txt += "<h2>" + myObj[x].title + "</h2><p>" + myObj[x].description + "</p><br/>"; 
     txt += "<h3>" + myObj[x].contents.title + "</h3><p>" + myObj[x].contents.description + "</p><br/>"; 
    } 

    document.getElementById("MAS").innerHTML = txt; 
    } 
}; 

request.send(); 
</script> 

這裏是JSON文件:

{ 
    "id": "life-events", 
    "type": "category", 
    "title": "Life events", 
    "description": "When big things happen - having a baby, losing your job, getting divorced or retiring\n - it helps to be in control of your money\n", 
    "contents": [ 
     { 
      "id": "setting-up-home", 
      "type": "category", 
      "title": "Setting up home", 
      "description": "Deciding whether to rent or buy, working out what you can afford and managing\n money when sharing with others\n", 
      "contents": [ 
      ] 
     }, 
     { 
      "id": "young-people-and-money", 
      "type": "category", 
      "title": "Leaving school or college", 
      "description": "", 
      "contents": [ 
      ] 
     }, 
     { 
      "id": "having-a-baby", 
      "type": "category", 
      "title": "Having a baby", 
      "description": "", 
      "contents": [ 
      ] 
     } 
    ] 
}, 

嵌套JSON是顯示爲 '未定義'。我如何訪問嵌套的數據?

我讀過有關這個話題無數帖子,但沒有在這種情況下確實幫助

+1

內容是一個對象數組。您需要循環訪問並獲取myObj [x] .contents [y] .title。 – Christopher

+1

@Christopher我也注意到了。你應該發佈這個答案。 –

+0

@LuisEstevez你可以繼續前進,如果你願意。我在我的手機上,所以這有點麻煩。 :) – Christopher

回答

2

你需要循環的contents以及因爲他們陣象下面這樣:

for (x in myObj) { 
    txt += "<h2>" + myObj[x].title + "</h2><p>" + myObj[x].description + "</p><br/>"; 
    for(y in myObj[x].contents){ 
    txt += "<h3>" + myObj[x].contents[y].title + "</h3><p>" + myObj[x].contents[y].description + "</p><br/>"; 
    } 
    } 

這裏一個JSBin

+0

我想,OP要第3行留在外層循環,只是說' – Christopher

+0

@Christopher是的,你說得對:) – Lotus91

+0

感謝Lotus91,這工作 –

1

您不能訪問myObj[x].contents.title,因爲contents是一個數組。需要爲其屬性重複myObj[x].contents