thadeuszlay thadeuszlay - 2 months ago 8
Javascript Question

load json file in nodejs/express app into d3

I have an express app and I want to load json-data from the folder

public
into d3 (version 4).

My folder structure looks like this:

public
|-myData.json
view
|-index.jade
app.js


The json data I want to load with d3:

{
{
"name": "Maria",
"age": 30
}, {
"name": "Fred",
"age": 50
}, {
"name": "Francis",
"age": 12
}
}


This is my index.jade file:

extends layout
block content
script(src='javascripts/jquery-3.1.1.min.js')
script(src='javascripts/d3.min.js')
script.
$(document).ready(function() {
d3.json("myData.json", function(data) {
console.log("d ", data);
});
});


In app.js I said that I want to serve static files:

app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static('public'));


In the console it always says:
d null


Update:
I now changed the path to

"d3.json("../myData.json", function(data)"


Looking into the network tab, I can see that it loads the file successfully. But in the console it would still print "
null
"

Update 2:
It was because of my JSON - data that was invalid. ^^

{
"content": [

{
"name": "Maria",
"age": 30
}, {
"name": "Fred",
"age": 50
}, {
"name": "Francis",
"age": 12
}
]
}

Answer

Make sure you point to the public folder in the first argument of d3.json in respect to where express is statically hosting the files.

...
d3.json("../myData.json", function(data) {
        console.log("d ", data);
      });
    });

Update: Edited answer to correct directory reference. Also be sure myData.json is a valid json file! :)