我希望从文件中加载JSON数据数组,以根据此处的Mike Bostock示例生成可折叠树形图.该示例使用格式正确的外部JSON文件,并使用d3.json函数加载它.
我希望能够从文件中加载一个json数组,这是从flay数组生成多级数组的结果(根据这里的示例问题).
一个我已经站了起来bl.ocks.org样本文件/ GitHub上显示的是什么,我想实现,而不采取多层次的JSON数据,并将其加入到可折叠的树形图中的重要组成部分两个部分
简而言之.我在文件中声明了以下数据;
var data = [
{ "name" : "ABC", "parent":"DEF", "relation": "ghi", "depth": 1 },
{ "name" : "DEF", "parent":"null", "relation": "null", "depth": 0 },
{ "name" : "new_name", "parent":"ABC", "relation": "rel", "depth": 2 },
{ "name" : "new_name2", "parent":"ABC", "relation": "foo", "depth": 2 },
{ "name" : "Foo", "parent":"DEF", "relation": "rel", "depth": 2 }
];
Run Code Online (Sandbox Code Playgroud)
然后通过这部分代码运行...
var dataMap = data.reduce(function(map, node) {
map[node.name] = node;
return map;
}, {});
// create the tree array
var treeData = [];
data.forEach(function(node) {
// add to parent
var parent = dataMap[node.parent];
if (parent) {
// create child array if it doesn't exist
(parent.children || (parent.children = []))
// add node to child array
.push(node);
} else {
// parent is null or missing
treeData.push(node);
}
});
Run Code Online (Sandbox Code Playgroud)
它将数组转换为多级json,如下所示(它也被推送到屏幕上供参考);
[
{
"name": "DEF",
"parent": "null",
"relation": "null",
"depth": 0,
"children": [
{
"name": "ABC",
"parent": "DEF",
"relation": "ghi",
"depth": 1,
"children": [
{
"name": "new_name",
"parent": "ABC",
"relation": "rel",
"depth": 2
},
{
"name": "new_name2",
"parent": "ABC",
"relation": "foo",
"depth": 2
}
]
},
{
"name": "Foo",
"parent": "DEF",
"relation": "rel",
"depth": 2
}
]
}
]
Run Code Online (Sandbox Code Playgroud)
但是我必须从外部文件加载相同的数据才能将其放入可折叠的树形图中.执行此操作的代码如下;
d3.json("example.json", function(error, DEF) {
root = DEF;
root.x0 = height / 2;
root.y0 = 0;
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
root.children.forEach(collapse);
update(root);
});
Run Code Online (Sandbox Code Playgroud)
图表看起来像这样......
我很确定我刚刚遇到某种心理障碍,这是一个简单的答案,但它已经打败了我几个小时了.
如何将正确格式化的JSON数据从代码的格式化部分传递到图表部分?
谢谢你的帮助.
编辑:我在这里添加了一个JSFiddle与耶稣建议的编辑(http://jsfiddle.net/LGvha/).
小智 9
您非常接近,您需要做的就是将您创建的treeData设置为树的根.因此,您可以执行以下操作,而不是加载JSON数据:
// replace this line
// d3.json("/d/4063550/flare.json", function(error, flare) {
root = treeData[0];
root.x0 = height / 2;
root.y0 = 0;
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
root.children.forEach(collapse);
update(root);
//remove this line
// });
Run Code Online (Sandbox Code Playgroud)