简体   繁体   中英

How to load JSON array from file NodeJS?

How should you load JSON array from file in NodeJS?

var fs = require('fs');
fs.readFile('input.json', (err, fileContent) => {
    if( err ) {
    } else {
      data = JSON.parse(fileContent);
      console.log(fileContent);
    }
})

input.json

[
{ "date": "2017-02-18" },
{ "date": "2017-02-18" },
]

Getting error: SyntaxError: Unexpected token ] in JSON at position

Make sure JSON is valid. ie, no trailing commas.

If you are loading something like a configuration, simply const data = require('./json-file.json') .

node can simply require json files natively. however this is synchronous. So only use it for something like loading a config in start-up.

Update input.json it contains one extra comma( , ) at the end before closing bracket ( ] )

[
{ "date": "2017-02-18" },
{ "date": "2017-02-18" }
]

and If you are reading json file in node.js and want to show data in json then place UTF8 while reading the file

var fs = require('fs');
fs.readFile('input.json', 'utf8',(err, fileContent) => {
    if( err ) {
    } else {
      data = JSON.parse(fileContent.toString());
      console.log(fileContent);
      console.log(data);
    }
})

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