使用json数据的D3.js data()方法

时间:2015-11-22 15:57:42

标签: javascript d3.js

我有一个包含5个对象的json字符串。我试图绘制五个rect s(与json数据中的对象数相同)但是渲染的rect比我预期的要多。{
有什么问题?

//json: [{"name":"136","count":1},{"name":"142","count":1},{"name":"147","count":1},{"name":"150","count":3},{"name":"152","count":5}]

var svg = d3.select(".wrapper")
            .append("svg")
            .attr("width", 500)
            .attr("height", 500);

svg.selectAll("rect")
.data(json)
.enter()
.append("rect")
.attr("y", function (d, i) { return 100+i*24; })
.attr("x", 0)
.attr("width", 500)
.attr("height", 20);

1 个答案:

答案 0 :(得分:0)

您将JSON视为字符串,而不是将其解析为对象。你应该做的

JSON.parse(yourJsonString);

比较一下:



var json = '[{"name":"136","count":1},{"name":"142","count":1},{"name":"147","count":1},{"name":"150","count":3},{"name":"152","count":5}]';

var svg = d3.select("body")
  .append("svg")
  .attr("width", 500)
  .attr("height", 500);

svg.selectAll("rect")
  .data(json)
  .enter()
  .append("rect")
  .attr("y", function(d, i) {
    return 100 + i * 24;
  })
  .attr("x", 0)
  .attr("width", 500)
  .attr("height", 20);

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
&#13;
&#13;
&#13;

对此:

&#13;
&#13;
var json = JSON.parse('[{"name":"136","count":1},{"name":"142","count":1},{"name":"147","count":1},{"name":"150","count":3},{"name":"152","count":5}]');

var svg = d3.select("body")
  .append("svg")
  .attr("width", 500)
  .attr("height", 500);

svg.selectAll("rect")
  .data(json)
  .enter()
  .append("rect")
  .attr("y", function(d, i) {
    return 100 + i * 24;
  })
  .attr("x", 0)
  .attr("width", 500)
  .attr("height", 20);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
&#13;
&#13;
&#13;