在html中显示嵌套的json对象

时间:2019-06-10 00:05:43

标签: javascript html arrays json object

我想在网页上显示收到的消息。我有一个指向JSON文件的网址,数据看起来像这样……

[
    {
      "created_at": "2019-06-08T10:30:52Z",
      "data": {
        "name": "Me",
        "email": "me@example.com",
        "is-org-bedrijf": "on",
        "org-bedrijf": "",
        "onderwerp": "meer info",
        "bericht": "bericht",
        "job-logo-deadline": "",
        "digitaal-deadline": "",
        "drukwerk-deadline": "",
        "flex-floc-kleuren": "transparant",
        "job-flex-floc-deadline": "",
        "andere-beschrijving": "",
        "andere-deadline": "",
        "g-recaptcha-response": ""
      },
      "folder": null,
      "id": 3250210,
      "referrer": "https://lennertderyck.be/contact/form",
      "request_ip": "78.23.211.248",
      "spam": null
    }
]

如何在javascript循环中访问信息?显示数据不是问题,它正在访问嵌套对象中的数据。

这是我尝试过的

 fetch('file.json')
            .then(function (response) {
                return response.json();
            })
            .then(function (source) {
                appendData(source);
            })
            .catch(function (err) {
                console.log('error: ' + err);
            });
        function appendData(source) {
            var mainContainer = document.getElementById("myData");
            for (var i = 0, il = source.length; i < il; i++) {
                    var div = document.createElement("div");
                    div.innerHTML = 'Id: ' + source[i].id;
                    mainContainer.appendChild(div);
                for (var j = 0; jl = source[i].data.length; j++) {
                    console.log(source[i].data[j].name)
                }
            }
        }

1 个答案:

答案 0 :(得分:1)

因为那不是您遍历对象的方式。像这样for...in循环来完成它:

for (var item in source[i].data) {
    console.log(source[i].data[item].name);
}