简体   繁体   中英

d3 library installed with npm doesn't load json file

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?

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'); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM