简体   繁体   中英

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. The JSON-file is however written in a way I'm not familiar with. 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. The result from the JSON-file in the output in the console gives (with slight modifications in the variable names):

{
    "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. 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.

The numerals 1007 and 1337 are properties of the object sites . Use a for-in loop to iterate through the object properties.

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(). 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 */
  }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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