Best way to format a JSON for D3 Forced Directed Best way to format a JSON for D3 Forced Directed json json

Best way to format a JSON for D3 Forced Directed


The force layout expects two arrays: An array of objects that are the nodes, which can have whatever attributes, and an array of links, which are objects that need to have a .source and .target attribute that point to the array position of the nodes that they link. Whatever you export should be an array of JSON objects for the nodes and use some kind of hash to translate the id values of source and target to the array position of those objects in that array.

So if you've got:

 nodes = [{name:"nodeA"},{name:"nodeB"},name:"nodeC"]

..then a link in the link array between those two would look like this:

 links = [{name: "linkA", source: 0, target: 1}, {name: "linkB", source: 2, target: 0}]

Note that it's pointing to the x of nodes[x] of the node object, and not an arbitrary id value. So the first link connects NodeA and NodeB, while the second connects NodeC and NodeA. So when you export your nodes, you need to keep track of their array position for your edges.