簡體   English   中英

如何使用 D3 訪問此 JSON 數據?

[英]How do I access this JSON data using D3?

我知道在 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 ?

嘗試這個

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

暫無
暫無

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

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