Search code examples
javascriptnode.jsjsonnpmreadfile

Read json file ignoring custom comments


How can i read this file 'file.json':

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

and retrieve the json 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

Have npm some package to solve this question?


Solution

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

    you can use json5 module