Jordan Hanna
Jordan Hanna

Reputation: 145

Best way to format a JSON for D3 Forced Directed

I'm currently using a Neo4j Graph DB to hold data from a network traffic pcap. I'm able to perform queries, and get a resulting JSON, but I am having a hard time finding an easy way to format the JSON into the node: link: format needed for D3's force directed graph!

Any help would be appreciated, I can't seem to find any links to the JSON formatting portion of creating this D3 graph.

Upvotes: 3

Views: 3352

Answers (1)

Elijah
Elijah

Reputation: 4639

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.

Upvotes: 4

Related Questions