Geert-Jan
Geert-Jan

Reputation: 18905

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:

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

Upvotes: 3

Views: 3846

Answers (3)

Steve Bennett
Steve Bennett

Reputation: 126255

HJSON meets all these requirements.

  • It's an NPM package
  • It can handle // comments
  • It can handle /* */ comments
  • It can handle unquoted keys.

You can try it online.

The sample text:

{
  # specify rate in requests/second (because comments are helpful!)
  rate: 1000

  // prefer c-style comments?
  /* feeling old fashioned? */

  # did you notice that rate doesn't need quotes?
  hey: look ma, no quotes for strings either!

  # best of all
  notice: []
  anything: ?

  # yes, commas are optional!
}

Upvotes: 2

Andrey Tarantsov
Andrey Tarantsov

Reputation: 9073

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
  ]
}

Upvotes: -1

Brad
Brad

Reputation: 163262

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')));

Upvotes: 4

Related Questions