我正在尝试使用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显示为“Undefined”。如何访问嵌套数据?
我已经阅读了关于这个主题的无数帖子,但在这个例子中没有一个真正有帮助
答案 0 :(得分: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。
答案 1 :(得分:1)
由于myObj[x].contents.title
是一个数组,因此您无法访问contents
。需要为其{s>属性迭代myObj[x].contents
。