使用JavaScript从JSON中的对象中提取对象

时间:2016-08-17 12:58:02

标签: javascript json

所以,我可以访问一个JSON文件,我应该以一种整洁的方式列出一些项目。然而,JSON文件是以我不熟悉的方式编写的。我有以下代码:

function readFile(file) {
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if (rawFile.readyState === 4 && rawFile.status === 200)
        {
            window.openedFile = JSON.parse(rawFile.responseText);
            console.log(JSON.stringify(openedFile, undefined, 4));
            createList();

        }
    };
    rawFile.send();
}


function createList() {
    var table = document.createElement('table');
    var body = document.createElement('tbody');

    for (var i = 0; i < openedFile.sites.length; i++) {
        var item = document.createElement('tr');
        var colSite = document.createElement('td');
        colSite.appendChild(document.createTextNode(openedFile.sites[i].name));
        item.appendChild(colSite);
        body.appendChild(item);
    }

    table.appendChild(body);
    document.getElementById('list').appendChild(table);
}

..它不起作用,因为它声称阵列&#34;网站&#34;是空的。控制台输出中的JSON文件的结果给出了(稍微修改了变量名称):

{
    "sites": {
        "1007": {
            "id": 1007,
            "name": "Location B",
            "devices": {
                "p3": {
                    "name": "p3",
                    "version": "5"
                }
            }
        },
        "1337": {
            "id": 1337,
            "name": "Location A",
            "devices": {
                "p2": {
                    "name": "p2",
                    "version": "5"
                },
                "p1": {
                    "name": "p1",
                    "version": "5"
                }
            }
        }
    },
}

如果我更改JSON文件并在网站后添加[]括号并删除&#34; 1007&#34;和&#34; 1337&#34;它看起来像我以前(作为一个普通的数组),它的工作原理。我很确定我不允许这样做,但在尝试提取有关设备的信息时我又遇到了同样的问题。我很感激你对此事的任何帮助。为了澄清,如果有其他解决方案,我试图避免更改JSON文件。

2 个答案:

答案 0 :(得分:2)

数字1007和1337是对象sites的属性。使用for-in循环迭代对象属性。

var sites = openedFile.sites;
for(var site in sites){
    console.log("Key: ", site);
    console.log("Value: ", sites[site]);
}

答案 1 :(得分:2)

站点是一个对象,而不是一个数组,因此您需要迭代对象的属性,而不是数组的元素。

要获取这些属性的列表,可以使用Object.keys()。这会为您提供一系列属性名称。

一旦有了这个数组,你就迭代它,每次都使用当前元素,这是原始对象属性的名称。

例如,这可行(只是控制台记录对象名称,你已经得到的提取):

function createList2() {
   var len = Object.keys(openedFile.sites); //get array of property keys
   for (var i of len) { //iterate over the array of property keys
    console.log(openedFile.sites[i].name); /*retrieve properties  by key from original object */
  }
}