Nodejs: any library to clean json (say comments) when reading from file?

I'm reading json files in Node.js using require("fs").

Something like:

var readJsonFromFile= function(fileLocation, callback){
      fs.readFile(fileLocation, 'utf8', function (err, data) {
          if (err) {
            return callback(err);
          }

          data = JSON.parse(data);
          callback(null,data);
    });
}

However, I noticed JSON.parse:

  • doesn't allow comments // bla or /* blaa */
  • requires keys to be quoted.

Although I realize this is technically correct, I'd like to know if any small library exists which cleans my often annotated json-files to guarentee the above. (And no, it's not completely trivial DIY, think // as part of valid values, etc. )

Thanks

Yes! I use JSON.minify by Kyle Simpson for this very purpose:

https://github.com/getify/JSON.minify

It isn't a full-blown Node module, but it works very well for loading JSON-like config files and such. Note that you still have to quote your keys, but it does allow for comments.

var config = JSON.parse(JSON.minify(fs.readFileSync(configFileName, 'utf8')));

Just use JS-YAML to parse your JSON files. YAML is a superset of JSON and supports the features you want.

You don't need to actually use any YAML-specific stuff in your config file if you don't want to; simply use YAML parser as a JSON parser that fixes 3 annoying problems (comments, quoting and trailing commas).

It even comes with a command-line tool to translate YAML into plain JSON:

~> echo "{ foo: 10, bar: [20, 30], }" | js-yaml -j /dev/stdin
{
  "foo": 10,
  "bar": [
    20,
    30
  ]
}