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?
So while JSON is often closely associated with JavaScript (even though it's used by most other languages as well), it does not support the same commenting features as JavaScript as it's a data-only specification. Comments were removed from the JSON specification because they were being used as parsing directives, which ...
If you're having trouble adding comments to your JSON file, there's a good reason: JSON doesn't support comments.
Open the JSON file in your text editor and add comments the same way you would in Python (using # and not docstrings) or the same way you would in JavaScript (using // and not multi-line comments using /** */ ).
The difference is: json() is asynchronous and returns a Promise object that resolves to a JavaScript object. JSON. parse() is synchronous can parse a string to (a) JavaScript object(s).
The perfect package for this problem is https://www.npmjs.com/package/hjson
hjsonText input:
{
# hash style comments
# (because it's just one character)
// line style comments
// (because it's like C/JavaScript/...)
/* block style comments because
it allows you to comment out a block */
# Everything you do in comments,
# stays in comments ;-}
}
Usage:
var Hjson = require('hjson');
var obj = Hjson.parse(hjsonText);
var text2 = Hjson.stringify(obj);
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With