TeachMeToAim TeachMeToAim - 3 months ago 8
JSON Question

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.

Answer

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