EN VI

Javascript - d3.json - how to replace URL with object/dynamic data?

2024-03-09 23:30:04
Javascript - d3.json - how to replace URL with object/dynamic data?

New to d3. Creating a sankey diagram. Found a sample that uses an external .json file. The sample uses d3.v3. I know that is old, but I have a tree that also uses that version, so I would prefer to just load one d3 version. The sankey works fine, but I want to replace the static json will with dynamic data pulled from a database. I would load the page, query the database, retrieve my data, and format it as an array of objects, passing the array to the sankey code.

Starting with small changes, I have copied the contents of the json file and inserted it into my page.

var MYDATA = {
"links": [
{"source":"Agricultural Energy Use","target":"Carbon Dioxide","value":"1.4"},
{"source":"Agriculture","target":"Agriculture Soils","value":"5.2"},
{"source":"Agriculture","target":"Livestock and Manure","value":"5.4"},
{"source":"Agriculture","target":"Other Agriculture","value":"1.7"},
...
};

The relevant sankey code - where the file is loaded - is

d3.json("#APP_FILES#sankeygreenhouse.json", function(error, graph) {
    var nodeMap = {};
    graph.nodes.forEach(function(x) { nodeMap[x.name] = x; });
    graph.links = graph.links.map(function(x) {
      return {
        source: nodeMap[x.source],
        target: nodeMap[x.target],
        value: x.value
      };
    });

I am trying to change this to use MYDATA instead of '#APP_FILES#sankeygreenhouse.json' I have tried changing this line to

d3.json(MYDATA, function(error, graph) {

but this just gives a 404 error. How do I make this work?

Solution:

d3.json loads a file and puts it into an object (in the above case, graph). By declaring it in an object, you're skipping that step, and putting it in MYDATA. You can just directly assign graph to MYDATA like so:

Change:

d3.json(MYDATA, function(error, graph) {
    var nodeMap = {};
    graph.nodes.forEach(function(x) { nodeMap[x.name] = x; });
    graph.links = graph.links.map(function(x) {
      return {
        source: nodeMap[x.source],
        target: nodeMap[x.target],
        value: x.value
      };
    });
//...
})

to

var nodeMap = {};
var graph = MYDATA;
// or if you want to make a copy:
// var graph = structuredClone(MYDATA);

graph.nodes.forEach(function(x) { nodeMap[x.name] = x; });
graph.links = graph.links.map(function(x) {
   return {
    source: nodeMap[x.source],
    target: nodeMap[x.target],
    value: x.value
   };
});
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login