Hemã Vidal Hemã Vidal - 1 year ago 64
JSON Question

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?

Answer Source

You can use your own RegExp pretty easily to match the comments beginning with a #

const matchHashComment = new RegExp(/(#.+)/, 'gi');
const fs = require('fs');

fs.readFile('./file.json', (err, data) => {
    // replaces all hash comments & trim the resulting string
    let json = data.toString('utf8').replace(matchHashComment, '').trim();  
    json = JSON.parse(json);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download