【发布时间】: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。我不明白这个。
所以我的问题是:
- 如何访问
unique_items中的元素? - 有没有更好的 json 结构方式?
【问题讨论】:
标签: javascript json d3.js