我使用D3绘制气泡图,使用json格式的数据绘制气泡图
我的json格式如下:{"children":[
{"name":"1","size":0.5},
{"name":"3","size":0.3636},
{"name":"4","size":0.5652},
{"name":"5","size":19.5556},
{"name":"6","size":1.037},
{"name":"7","size":0.7048},
{"name":"8","size":2.2593},
{"name":"9","size":13.7407},
{"name":"10","size":4.2222},
{"name":"11","size":2.6667},
{"name":"12","size":0.7037},
{"name":"13","size":20.6296},
{"name":"14","size":17.7037},
{"name":"15","size":2.1481},
{"name":"16","size":3.4815},
{"name":"17","size":0.1852},
{"name":"18","size":0.087},
{"name":"19","size":15.68}
]}
我正在访问这个json:
d3.json("flare.json", function(error, root) {
var node = svg.selectAll(".node")
.data(bubble.nodes(classes(root))
.filter(function(d) { return !d.children; }))
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
现在我想从可靠的访问
var datasource = {"children":[
{"name":"1","size":0.5},
{"name":"3","size":0.3636},
{"name":"4","size":0.5652},
{"name":"5","size":19.5556},
{"name":"6","size":1.037},
{"name":"7","size":0.7048},
{"name":"8","size":2.2593},
{"name":"9","size":13.7407},
{"name":"10","size":4.2222},
{"name":"11","size":2.6667},
{"name":"12","size":0.7037},
{"name":"13","size":20.6296},
{"name":"14","size":17.7037},
{"name":"15","size":2.1481},
{"name":"16","size":3.4815},
{"name":"17","size":0.1852},
{"name":"18","size":0.087},
{"name":"19","size":15.68}
]}
我试过像:
JSON.parse("dataSource", function(error, root) {
var node = svg.selectAll(".node")
.data(bubble.nodes(classes(root))
.filter(function(d) { return !d.children; }))
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
但无法得到我出错的结果。请回复我。
由于 prashansa
答案 0 :(得分:1)
datasource
是变量而不是字符串
所以试试这个
JSON.parse(dataSource, function(error, root) {
EDITED
var dataSource = '{"children":...'; //JSON.parse needed
//so your code would be
JSON.parse(dataSource, function(error, root) {
var dataSource = {"children":...}; //JSON.parse not needed
//so your code would be
var node = svg.selectAll(".node")
.data(bubble.nodes(classes(dataSource))
.filter(function(d) { return !d.children; }))