簡體   English   中英

使用 JS 解析 JSON 嵌套數組

[英]Parsing JSON nested arrays with JS

我在這里討論了類似 JSON 的各種主題,但從來沒有相同過,而且我仍在努力遍歷數組的元素。

我有以下 JSON:

     {
     "person": 
     [
        {
            "id": "xyz",
            "attributes": 
            [
            {"attribute_name1": "value1"},
            {"attribute_name2": "value2"}
            ]
        },
        {
            "id": "abc1",
            "attributes": 
            [
            {"attribute_name1": "value3"},
            {"attribute_name2": "value4"},
{"attribute_name3": "value77"}
            ]
        }
    ]
}

JSON 預先作為字符串傳遞。 然后我試圖列出所有“人”及其 ID 和屬性列表:

var data = '{"person":[ { "id": "xyz","attributes": [{"attribute_name1": "value1"},{"attribute_name2": "value2"}]},{"id": "abc1","attributes": [{"attribute_name1": "value3"},{"attribute_name2": "value4"},{"attribute_name3": "value77"}]}]}';

var json, i, j;
var json = data.toString();

json = JSON.parse(json);

for (i in json.person) {
  for (j in json.person[i].attributes) {
    var attribute_name = Object.keys(json.person[i].attributes[j]); // here because I won't know what are the actual names of those attributes
    console.log("Person's ID: " +json.person[i].id + " /// Person's Attribute name: " +attribute_name + " /// Person's Value: " +json.person[i].attributes[j]['attribute_name']);
    console.log("Person's Value: " +json.person[i].attributes[j]['attribute_name']); // this gives undefined
    console.log("Person's Value: " +json.person[i].attributes[j].attribute_name);    // this also gives undefined
  }
}

如果有任何幫助,我很高興更改 JSON 的結構。 如果它們的名稱不是“固定的”,有關如何獲取這些屬性名稱的值的任何提示?

也許這會有所幫助。 更改 JSON 結構

 var person = [{id:1, name: 'John'},{id:2, name: 'Mary'}]; var attributes = [ {person_id:1, name: 'attr_name', value: 'val1'}, {person_id:2, name: 'attr_name2', value: 'val2'} ]; // variant 1 for (let attr of attributes) { if (attr.person_id === targetPersonId) { ... } } // variant 2 attributes.map(el => el.person_id === targetPersonId).forEach(... do something)

您可以將此代碼段與現有的 JSON 結構一起使用。

const data = '{"person":[ { "id": "xyz","attributes": [{"attribute_name1": "value1"},{"attribute_name2": "value2"}]},{"id": "abc1","attributes": [{"attribute_name1": "value3"},{"attribute_name2": "value4"},{"attribute_name3": "value77"}]}]}';

const json = JSON.parse(data);

json.person.forEach((person) => {
  person.attributes.forEach((attribute) => {
    const properties = Object.keys(attribute);
    console.log(`Person's ID:`, person.id);
    properties.forEach((prop) => {
      console.log(`${prop} ${attribute[prop]}`);
    });
  });
});

json.person[i].attributes[j]['attribute_name']刪除單引號,即json.person[i].attributes[j][attribute_name]

var data = '{"person":[ { "id": "xyz","attributes": [{"attribute_name1": "value1"},{"attribute_name2": "value2"}]},{"id": "abc1","attributes": [{"attribute_name1": "value3"},{"attribute_name2": "value4"},{"attribute_name3": "value77"}]}]}';
var json, i, j;

json = JSON.parse(data);
for (i in json.person) {
  for (j in json.person[i].attributes) {
    var attribute_name = Object.keys(json.person[i].attributes[j]);
    console.log("Person's ID: " +json.person[i].id + " /// Person's Attribute name: " + attribute_name + " /// Person's Value: " +json.person[i].attributes[j][attribute_name]);
    console.log("Person's Value: " +json.person[i].attributes[j][attribute_name]);
  }
}

如果您想從 json 中獲取具有名稱/值的對象,您可以嘗試使用這樣的方法。

var object = {
     "person": 
     [
        {
            "id": "xyz",
            "attributes": 
            [
            {"attribute_name1": "value1"},
            {"attribute_name2": "value2"}
            ]
        },
        {
            "id": "abc1",
            "attributes": 
            [
            {"attribute_name1": "value3"},
            {"attribute_name2": "value4"},
            {"attribute_name3": "value77"}
            ]
        }
    ]
}



var someobj = {};

function generate(obj) {
    Object.keys(obj).forEach(key => {
        if (key !== 'key' && key !== 'value') {
            obj[key].forEach(element => {
                someobj[element.id] = element.attributes;
                return someobj;
            });
        }
    })
}

 <script> var data = { person: [{ id: "xyz", attributes: [{ attribute_name1: "value1" }, { attribute_name2: "value2" }] }, { id: "abc1", attributes: [{ attribute_name1: "value3" }, { attribute_name2: "value4" }, { attribute_name3: "value77" }] }] }; var json, i, j; //var json = data.toString(); //json = JSON.parse(json); for (i in data.person) { console.log("Person's ID: " + data.person[i].id); for (j in data.person[i].attributes) { var attribute_name = Object.keys(data.person[i].attributes[j])[0]; // here because I won't know what are the actual names of those attributes console.log("Person's Value: " +attribute_name +"->" + data.person[i].attributes[j][attribute_name]); // this gives undefined } } </script>

暫無
暫無

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

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