如何访问嵌套的 JSON 对象键和值

新手上路,请多包涵

我正在尝试像这样访问嵌套数组的键和值:

 var obj = $.getJSON("mydata.json", function() {
    console.log( "load success" );
});

Object.keys(obj[2].type).forEach(function(key) {
    console.log(key, obj[key]);
});

但是我得到一个错误。

这是 JSON 文件的结构:

 {
"nodes": [
    {
        "nd": "nd1",
        "cat": "cat1"
    }
],
"links": [
    {
        "id": 100
    }
],
"types": [
            {
                "type": "one",
                "image": "image001"
            },
            {
                "type": "two",
                "image": "image002"
            },
            {
                "type": "three",
                "image": "image003"
            }
        ]

}

我的目标是获得以下值的列表:

一二三

原文由 passion 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 683
2 个回答

像那样的东西?

您必须首先访问 object.types 属性,然后对其进行迭代以检索每种类型。

 var object = {
  "nodes": [{
    "nd": "nd1",
    "cat": "cat1"
  }],
  "links": [{
    "id": 100
  }],
  "types": [{
    "type": "one",
    "image": "image001"
  }, {
    "type": "two",
    "image": "image002"
  }, {
    "type": "three",
    "image": "image003"
  }]
};

function parseJson(object){
    object.types.forEach(function(key) {
      console.log(key.type);
    });
}

parseJson(object);

—更新以回答评论中的问题—

您可以将代码包含在一个函数中,并在加载 json 时调用它:

 $.getJSON("mydata.json", function(data) {
    parseJson(data);
});

原文由 GiuServ 发布,翻译遵循 CC BY-SA 3.0 许可协议

你可以用这段代码来做到这一点:

 var obj = {
"nodes": [
    {
        "nd": "nd1",
        "cat": "cat1"
    }
],
"links": [
    {
        "id": 100
    }
],
"types": [
            {
                "type": "one",
                "image": "image001"
            },
            {
                "type": "two",
                "image": "image002"
            },
            {
                "type": "three",
                "image": "image003"
            }
        ]
};

Object.keys(obj["types"]).forEach(function(key) {
    console.log(obj["types"][key].image);
});

原文由 Fermín 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题