繁体   English   中英

使用JavaScript读取嵌套的JSON

[英]reading nested JSON using JavaScript

我正在尝试使用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显示为“未定义”。 如何访问嵌套数据?

我读了无数有关此主题的文章,但在这种情况下没有任何帮助

您还需要遍历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

你不能访问myObj[x].contents.title因为contents是一个数组。 需要对其属性进行迭代myObj[x].contents

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM