javascript - 使用 JavaScript 读取嵌套 JSON

标签 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 显示为“未定义”。如何访问嵌套数据?

我读过无数关于这个主题的帖子,但没有一个对这个例子有真正的帮助

最佳答案

您还需要循环遍历内容,因为它们是如下所示的数组:

   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/

相关文章:

java - 消息负载的类型为 : BufferInputStream

java - google oauth2 如何获取服务帐户的私钥

javascript - React - 从目标中获取值(value)

javascript - 无法更改 d3.js 矩形的填充

javascript - 查找 Iron Router 中定义的所有路由

python - 给定一个字符串,如何返回 json 路径?

java - 使用 Gson 序列化 JSON 时包裹某些值

python - 预期关键数据类型不匹配 : S actual: L Dynamodb insert error with boto3

javascript - 匹配 jquery 中的两个字符串

javascript - javascript 数组中有新行时出错