I tried setting both nodes and links at the same time this way:
var force = d3.layout.force()
.size([w, h])
.nodes(nodes)
.links(connections)
Thanks to the answers above which refer to null source or target values!
I've been testing out the graph from http://bl.ocks.org/mbostock/4062045, and found that my data referenced a missing node.
This may help others debug this issue:
d3.json("my-buggy-data.json", function(error, graph) {
// Find blank links, which give the error
// "Uncaught TypeError: Cannot read property 'weight' of undefined"
graph.links.forEach(function(link, index, list) {
if (typeof graph.nodes[link.source] === 'undefined') {
console.log('undefined source', link);
}
if (typeof graph.nodes[link.target] === 'undefined') {
console.log('undefined target', link);
}
});
force
.nodes(graph.nodes)
.links(graph.links)
.start();