Reputation: 611
I just installed d3 using npm. In package.json
it shows on dependencies "d3": "^4.11.0" version,
.
I tried to load a simple json file with the next code:
const d3 = require('d3')
d3.json('jsonfile.json', (err, data) => {
if (err) {
console.log(err)
}
data.keys.map((t) => {
console.log(t)
})
})
But I got this error:
SyntaxError: Unexpected token T in JSON at position 0
The json file is actually ok. I verified using this tool: https://codebeautify.org/jsonvalidator.
However, when I removed this line const d3 = require('d3')
and inserted the script directly in the HTML file:
<script type='text/javascript' src='/js/d3.min.js'></script>
...using 3.5.5 version, the json file was loaded.
Is there something new in d3
version ^4.11.0
in order to load local files?
Upvotes: 0
Views: 868
Reputation: 39270
If you want to run your code as a node app you have to load json with the full url:
const d3 = require('d3');
//use full url to where the json file is
d3.json('http://localhost:8080/jsonfile.json', (err, data) => {
if (err) {
console.log(err)
}
data.keys.map((t) => {
console.log(t)
})
});
If you want to run the code as a node app and load the file from disk you could load the file like so:
fs = require('fs');
const readFile = (file,encoding) =>
new Promise(
(resolve,reject)=>
fs.readFile(
file
,encoding
,(err,data) => {
if(err !== null){
reject(err);return;
}
resolve(data);
}
)
)
;
readFile("./static/jsonfile.json",'utf8')
.then(
data =>
data.toString()
).then(
text =>
console.log("Got file content:\n",text)
,err =>
console.error("Failed to load file:",err)
);
If your code runs in a browser but you want to use npm as dependency management then you can use requirejs (old way) or webpack (better but a bit more complicated to learn and set up). If you are using your code in a browser I wonder how you do not get an error on const d3 = require('d3');
.
Upvotes: 1