在D3中访问嵌套JSON结构 [英] Accessing nested JSON structure in D3
问题描述
我正在尝试使用D3创建一组图形,我无法弄清楚如何访问JSON中的嵌套数据结构。数据看起来像这样(截断):
I'm trying to create a set of graphs using D3 and I'm having trouble figuring out how to access nested data structures in my JSON. The data looks something like this (truncated):
{ "date": "20120927",
"hours": [
{ "hour": 0, "hits": 823896 },
{ "hour": 1, "hits": 654335 },
{ "hour": 2, "hits": 548812 },
{ "hour": 3, "hits": 512863 },
{ "hour": 4, "hits": 500639 }
],
"totalHits": "32,870,234",
"maxHits": "2,119,767",
"maxHour": 12,
"minHits": "553,821",
"minHour": 3 }
{ "date": "20120928",
"hours": [
{ "hour": 0, "hits": 1235923 },
{ "hour": 1, "hits": 654335 },
{ "hour": 2, "hits": 1103849 },
{ "hour": 3, "hits": 512863 },
{ "hour": 4, "hits": 488506 }
],
"totalHits": "32,870,234",
"maxHits": "2,119,767",
"maxHour": 12,
"minHits": "553,821",
"minHour": 3 }
我最终想要做的是创建多个雷达图,每天一个,绘制每小时的点击。但我有麻烦,即使只是进入小时数组。例如,我可以得到所有日期的列表,例如:
What I eventually want to do is create multiple radar graphs, one for each day, plotting the hits for each hour. But I'm having trouble even just getting inside the "hours" array. I can , for example, get a list of all the dates, like so:
d3.select("body")
.append("ul")
.selectAll("li")
.data(data)
.enter()
.append("li")
.text(function (d,i) {
return d.date;
});
但我不能得到任何更多的嵌套。
But I can't get at anything more nested. Can someone help point me in the right direction?
推荐答案
假设数据
是一个包含两个对象的双元素数组,你可以这样做:
Assuming data
is an two-element array containing your two objects, you could do something like this:
d3.select("body").append("ul").selectAll("li")
.data(data) // top level data-join
.enter().append("li")
.each(function() {
var li = d3.select(this);
li.append("p")
.text(function(d) { return d.date; });
li.append("ul").selectAll("li")
.data(function(d) { return d.hours; }) // second level data-join
.enter().append("li")
.text(function(d) { return d.hour + ": " + d.hits; });
});
这将给你一个这样的嵌套结构:
This would give you a nested structure like this:
<ul>
<li>
<p>20120927</p>
<ul>
<li>0: 823896</li>
<li>1: 654335</li>
<li>2: 548812</li>
<li>3: 512863</li>
<li>4: 500639</li>
</ul>
</li>
<li>
<p>20120928</p>
<ul>
<li>0: 1235923</li>
<li>1: 654335</li>
<li>2: 1103849</li>
<li>3: 512863</li>
<li>4: 488506</li>
</ul>
</li>
</ul>
另请参阅Mike的嵌套选择文章。
See also Mike's Nested Selections article.
这篇关于在D3中访问嵌套JSON结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!