Hemã Vidal Hemã Vidal - 17 days ago 6
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

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);
    console.log(json);
});
Comments