2015-11-22 40 views
0

我有一個json字符串,它有5個對象。我試圖繪製五個rect(與json數據中的對象數量相同),但是渲染的數量比我預期的要多。
問題是什麼?使用json數據的D3.js data()方法

//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); 

回答

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>

要這樣:

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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>