【问题标题】:How do I access this JSON data using D3?如何使用 D3 访问此 JSON 数据?
【发布时间】:2016-09-15 22:03:51
【问题描述】:

我知道在 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 结构方式?

【问题讨论】:

    标签: javascript json d3.js


    【解决方案1】:

    试试这个

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

    【讨论】:

    • 解决了!我明白当时发生了什么。第一次迭代只是获取它在数组 (0) 中的索引/位置,然后我仍然需要使用它通过它在数组中的索引来访问该项目。谢谢!
    • 如果您在developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 中使用 for .. of .. 而不是 for ..,那么您的想法是正确的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-24
    • 2017-03-27
    • 2021-07-02
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多