如何使用D3访问此JSON数据?

时间:2016-09-15 22:03:52

标签: javascript json d3.js

我知道在D3中加载JSON就是这样完成的,这不会产生任何错误:

d3.json("sample_data/unique_items.json", function(json) {
  // do something
});

在这个块中,我然后使用json变量引用json文件。以下是JSON的示例结构:

{
  "unique_items": [
    {
      "name": "Blah",
      "items": [
        {"id": 1, "note": "blah"},
        {"id": 2, "note": "blah blah"},
        {"id": 3, "note": "blah blah blah"}
      ]
    },
    {
      "name": "Blah2",
      "items": [
        {"id": 1, "note": "blah"},
        {"id": 2, "note": "blah blah"},
        {"id": 3, "note": "blah blah blah"}
      ]
    }
  ]
}

我正在努力解决如何访问此结构中的项目的问题。所以我举例说这是一个测试:

for (var item in json["unique_items"]) {
  if (json["unique_items"].hasOwnProperty(item)) {
    console.log(item["name"]);  // 'undefined' error on this line
  }
}

我在上面注释的行上得到了一个未定义的错误。我希望在控制台中看到这个:

Blah
Blah2

我尝试将该行更改为console.log(item.name);,但这会产生相同的错误。然后我将该行更改为console.log(item);,并且控制台的输出为0。我不明白这一点。

所以我的问题是:

  1. 如何访问unique_items中的元素?
  2. 是否有更好的方式来构建json?

1 个答案:

答案 0 :(得分:1)

试试这个

for (var key in json["unique_items"]) {
  var item = json["unique_items"][key];
  if (item) {
    console.log(item["name"]);
  }
}
相关问题