簡體   English   中英

使用JavaScript從JSON對象中提取對象

[英]Extract objects from object in JSON using JavaScript

因此,我可以訪問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);
}

..並且它不起作用,因為它聲稱數組“ sites”為空。 控制台輸出中的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文件並在站點后添加[]括號並刪除“ 1007”和“ 1337”,則看起來我已經習慣了(作為普通數組),並且可以正常工作。 我敢肯定,我不允許這樣做,並且在嘗試提取有關設備的信息時,我再次遇到相同的問題。 對此,我將不勝感激。 為了澄清起見,如果有其他解決方案,我將盡量避免更改JSON文件。

數字1007和1337是對象sites屬性。 使用for-in循環迭代對象屬性。

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

站點是對象,而不是數組,因此您需要遍歷對象的屬性,而不是數組的元素。

為了獲得這些屬性的列表,可以使用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 */
  }
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM