我有一个包含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);
答案 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;
对此:
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;