Read json file ignoring user comments

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

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

and get json without comment?

I am 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

Is there npm some package to solve this issue?

+4
source share
3 answers

Ideal package for this problem - https://www.npmjs.com/package/hjson

HjsonText input:

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

Using:

var Hjson = require('hjson');

var obj = Hjson.parse(hjsonText);
var text2 = Hjson.stringify(obj);
+1
source

The package you are looking for is called strip-json-comments - https://github.com/sindresorhus/strip-json-comments

const json = '{/*rainbows*/"unicorn":"cake"}';

JSON.parse(stripJsonComments(json)); //=> {unicorn: 'cake'}
+1
source

RegExp , #

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);
});
+1

Source: https://habr.com/ru/post/1661235/


All Articles