Accessing nested JSON structure in D3

2020-08-05 06:02发布

问题:

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?

回答1:

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>

See also Mike's Nested Selections article.