简体   繁体   English

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

[英]Extract objects from object in JSON using JavaScript

So, I have access to a JSON-file and I'm supposed to list a few items in a neat fashion. 因此,我可以访问JSON文件,并且应该以简洁的方式列出一些项目。 The JSON-file is however written in a way I'm not familiar with. 但是,JSON文件是以我不熟悉的方式编写的。 I have the following code: 我有以下代码:

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);
}

..and it does not work as it claims the array "sites" is empty. ..并且它不起作用,因为它声称数组“ sites”为空。 The result from the JSON-file in the output in the console gives (with slight modifications in the variable names): 控制台输出中的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"
                }
            }
        }
    },
}

If I change the JSON-file and add [] brackets after sites and remove "1007" and "1337" it looks like I'm used to (as an ordinary array), and it works. 如果我更改JSON文件并在站点后添加[]括号并删除“ 1007”和“ 1337”,则看起来我已经习惯了(作为普通数组),并且可以正常工作。 I'm pretty sure I'm not allowed to do this however and I get the same problem again when trying to extract information about the devices. 我敢肯定,我不允许这样做,并且在尝试提取有关设备的信息时,我再次遇到相同的问题。 I would appreciate any help on this matter. 对此,我将不胜感激。 And to clarify, I'm trying to avoid changing the JSON-file, if there is some other solution. 为了澄清起见,如果有其他解决方案,我将尽量避免更改JSON文件。

The numerals 1007 and 1337 are properties of the object sites . 数字1007和1337是对象sites属性。 Use a for-in loop to iterate through the object properties. 使用for-in循环迭代对象属性。

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

Sites is an object, not an array, so you need to iterate over the object's properties, not the elements of the array. 站点是对象,而不是数组,因此您需要遍历对象的属性,而不是数组的元素。

In order to get a list of those properties, you can use Object.keys(). 为了获得这些属性的列表,可以使用Object.keys()。 That gives you an array of the property names. 这为您提供了一组属性名称。

Once you have that array, you iterate over it and each time use the current element, which is the name of the property of the original object. 一旦有了该数组,就可以对其进行迭代,并且每次都使用当前元素,这是原始对象的属性的名称。

For example, this works (just console logging the object name, the extraction you've already got): 例如,这有效(只需在控制台上记录对象名称,已经提取的内容):

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 */
  }
} 

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

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