我想使用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是顯示爲 '未定義'。我如何訪問嵌套的數據?
我讀過有關這個話題無數帖子,但沒有在這種情況下確實幫助
內容是一個對象數組。您需要循環訪問並獲取myObj [x] .contents [y] .title。 – Christopher
@Christopher我也注意到了。你應該發佈這個答案。 –
@LuisEstevez你可以繼續前進,如果你願意。我在我的手機上,所以這有點麻煩。 :) – Christopher