Reputation: 13
This is my code from the html file in script tag
var links;
d3.json("sample.json",function(json){links=json;});
var inputlinks=[];
var nodes = {};
inputlinks.push(links);
// Compute the distinct nodes from the links.
links.forEach(function(link) {
link.source = nodes[link.source] || (nodes[link.source] = {name: link.source, type:link.type});
link.target = nodes[link.target] || (nodes[link.target] = {name: link.target, type:link.typeKBP});
});
In this code am getting an error
TypeError: links is undefined
links.forEach(function(link)
Upvotes: 0
Views: 735
Reputation: 5749
From the information you provide I can only guess that you should include all your loginc inide the callback:
var links;
d3.json("sample.json",function(json){
links=json;
var inputlinks=[];
var nodes = {};
inputlinks.push(links);
// Compute the distinct nodes from the links.
links.forEach(function(link) {
link.source = nodes[link.source] || (nodes[link.source] = {name: link.source, type:link.type});
link.target = nodes[link.target] || (nodes[link.target] = {name: link.target, type:link.typeKBP});
});
});
Upvotes: 2
Reputation: 109232
As pointed out in the comments, d3.json
is an asynchronous call. This means that the code in the handler function will be run when it returns, not immediately. The code after it is run immediately though.
To fix, move the rest of the code inside the handler function:
d3.json("sample.json",function(json){
var links = json;
var inputlinks=[];
var nodes = {};
inputlinks.push(links);
// Compute the distinct nodes from the links.
links.forEach(function(link) {
link.source = nodes[link.source] || (nodes[link.source] = {name: link.source, type:link.type});
link.target = nodes[link.target] || (nodes[link.target] = {name: link.target, type:link.typeKBP});
});
});
Upvotes: 2