I am looking to extract node information from links data stored in a JSON file. My ultimate goal is to visualize this data by creating a graph with connections and edges.
Here is a snippet from my sample JSON file:
{
"links": [
{ "source":0, "target":1, "value":20, "orientation":"down" },
{ "source":1, "target":2, "value":1, "orientation":"left" },
{ "source":2, "target":3, "value":1, "orientation":"right" }
]
}
This is the JavaScript function I have implemented:
$(function() {
var width = 500,
height = 300;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var force = d3.layout.force()
.gravity(.05)
.distance(100)
.charge(-100)
.size([width, height]);
d3.json("test_1.json", function(error, json) {
if (error) throw error;
var count = 0;
var nodes = [];
json.links.forEach(function(e) {
count++;
nodes.push({name: "test_"+e.source, orientation: e.orientation});
});
console.log("Count is : "+count);
force
.nodes(json.nodes)
.links(json.links)
.start();
var link = svg.selectAll(".link")
.data(json.links)
.enter().append("line")
.attr("class", "link");
var node = svg.selectAll(".node")
.data(json.nodes)
.attr("class", "node")
.call(force.drag);
node.append("circle")
.attr("class", "node")
.attr("r", 5);
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
});
});
});
Unfortunately, I am encountering issues with extracting the list from the function due to an error related to the forEach method of JSON data structure.
If anyone could provide guidance or assistance, it would be greatly appreciated.
UPDATE: The complete code has been added for reference.
Error: Cannot read property 'weight' of undefined.
To resolve this issue, I included additional nodes in my JSON as D3.js always requires a node element in the dataset.