我想将强制网络可视化中的节点和边(链接)数据保存到JSON文件。
我在JSON文件中读取了源代码,并且在保存数据时我想要完全相同的格式。 我使用FileSaver.js(https://github.com/eligrey/FileSaver.js/)来创建JSON文件:
var blob = new Blob([JSON.stringify(graph)],
{type: "text/plain;charset=utf-8"});
saveAs(blob, "graphData.JSON");
问题是Force Network功能将source:
和target:
节点数组引用转换为节点数组中的值。这意味着我的源数据:
{
"nodesData":[
{"id":0,"label":"Zero","x":360,"y":40,"fixed":true},
{"id":1,"label":"One","x":620,"y":20,"fixed":true},
{"id":2,"label":"Two","x":620,"y":80,"fixed":true}
],
"edgesData":[
{"id":0,"source":0,
"target":1},
{"id":1,"source":0,
"target":2}
]
}
保存为:
{
"nodesData":[
{"id":0,"label":"Zero","x":360,"y":40,"fixed":true,"index":0,"weight":2,"px":360,"py":40},
{"id":1,"label":"One","x":620,"y":20,"fixed":1,"index":1,"weight":1,"px":620,"py":20},
{"id":2,"label":"Two","x":620,"y":80,"fixed":true,"index":2,"weight":1,"px":620,"py":80}
],
"edgesData":[
{"id":0,"source":{"id":0,"label":"Zero","x":360,"y":40,"fixed":true,"index":0,"weight":2,"px":360,"py":40},
"target":{"id":1,"label":"One","x":620,"y":20,"fixed":1,"index":1,"weight":1,"px":620,"py":20}
},
{"id":1,"source":{"id":0,"label":"Zero","x":360,"y":40,"fixed":true,"index":0,"weight":2,"px":360,"py":40},
"target":{"id":2,"label":"Two","x":620,"y":80,"fixed":true,"index":2,"weight":1,"px":620,"py":80}
}
]
}
我的目标是稍后将这个新保存的JSON文件加载到强制网络可视化中。但是,将文件重新加载为当前导出会导致链接构造失败。如何导出到与source:
和target:
引用的原始格式匹配的JSON文件?
答案 0 :(得分:3)
有多种方法可以恢复原始数据结构或操纵D3将source
和target
值与节点匹配的方式。最简单的方法是在序列化为JSON之前将edgesData
中的对象引用转换回基于索引或基于值的引用:
graph.edgesData.forEach(e => {
e.source = e.source.id;
e.target = e.target.id;
});
这样做会产生原始结构,现有代码将理解这一结构。
var graph = {
"nodesData":[
{"id":0,"label":"Zero","x":360,"y":40,"fixed":true,"index":0,"weight":2,"px":360,"py":40},
{"id":1,"label":"One","x":620,"y":20,"fixed":1,"index":1,"weight":1,"px":620,"py":20},
{"id":2,"label":"Two","x":620,"y":80,"fixed":true,"index":2,"weight":1,"px":620,"py":80}
],
"edgesData":[
{"id":0,"source":{"id":0,"label":"Zero","x":360,"y":40,"fixed":true,"index":0,"weight":2,"px":360,"py":40},
"target":{"id":1,"label":"One","x":620,"y":20,"fixed":1,"index":1,"weight":1,"px":620,"py":20}
},
{"id":1,"source":{"id":0,"label":"Zero","x":360,"y":40,"fixed":true,"index":0,"weight":2,"px":360,"py":40},
"target":{"id":2,"label":"Two","x":620,"y":80,"fixed":true,"index":2,"weight":1,"px":620,"py":80}
}
]
};
graph.edgesData.forEach(e => {
e.source = e.source.id;
e.target = e.target.id;
});
console.log(graph);