我正在尝试使用 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 显示为“未定义”。如何访问嵌套数据?
我读过无数关于这个主题的帖子,但没有一个对这个例子有真正的帮助
最佳答案
您还需要循环遍历内容
,因为它们是如下所示的数组:
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 .
关于javascript - 使用 JavaScript 读取嵌套 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43211542/