gpt4 book ai didi

javascript - 将 Force Network 数据保存到 JSON 文件

转载 作者:行者123 更新时间:2023-11-30 11:25:17 26 4
gpt4 key购买 nike

我想将力网络可视化中的节点和边(链接)数据保存到 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 文件?

最佳答案

有多种方法可以恢复原始数据结构或操纵 D3 将 sourcetarget 值与节点匹配的方式。最简单的方法是在序列化为 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);

关于javascript - 将 Force Network 数据保存到 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48291703/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com