javascriptnode.jsjsonnpmreadfile

Read JSON file ignoring custom comments


How can I read this file, 'file.json'?

# Comment01
# Comment02
{
   "name": "MyName"
}

And retrieve the JSON content without comments?

I'm using this code:

var fs = require('fs');
var obj;
fs.readFile('./file.json', 'utf8', function (err, data) {
  if (err) throw err;
  obj = JSON.parse(data);
});

It returns this error:

SyntaxError: Unexpected token # in JSON at position 0

Does npm have some package to solve this question?


Solution

  • Use:

    let json = require('json5')
    let fs = require('fs-extra')
    
    let a = json.parse(fs.readFileSync("./tsconfig.json"))
    console.log(a)
    

    You can use the 'json5' module.