Recently, I've been tasked with displaying items from a JSON-file in a well-organized manner. However, the format of the JSON file is unfamiliar to me. The code snippet provided below pertains to this task:
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);
}
Unfortunately, it seems that the code isn't working properly as it keeps indicating that the array "sites" is empty. The altered output of the JSON-file displayed on the console looks somewhat like this:
{
"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"
}
}
}
},
}
Upon modifying the JSON-file by adding [] brackets after sites and eliminating "1007" and "1337," the structure conforms to what I'm accustomed to (an ordinary array), which resolves the issue momentarily. However, I suspect this approach may not be permissible and poses a challenge when extracting device information. Any suggestions or assistance would be greatly appreciated. In essence, I'm seeking an alternative that doesn't involve altering the JSON-file.