/ nodejs

Parsing JSON files with NodeJS

It seems like every month or so, I'm trying to format a large JSON file I've downloaded or dumped from somewhere. Despite JSON being a very human readable, it isn't of much use if it isn't properly formatted.

There are plenty of ways to format it in the browser. You can always google "json formatter" and get back thousands of sites that will do it for you. You can even start up the dev console and run the native JavaScript function JSON.stringify on it. These tend to be limited the size of your clipboard, so these solutions will tend to choke once you get in the megabytes of text.

My go to solution has usually been python's json module on the command line (python -m json.tool), but I always seem to forget the exact module name and I have to search for it. Today, I came up with a simple command line tool that does it in Node. I've aliased it to jsonformat so it should be easy to remember later. Use it with jsonformat <file> -r and it will replace the file with a formatted version of it. There are also options to specify the output file and the amount of spaces to be used in formatting.

const fs = require('fs');
const config = {
  default: {
    r: false,
    o: 'output.json',
    s: '2'
  }
};
const argv = require('minimist')(process.argv.slice(2), config);
const jsonStr = fs.readFileSync(argv._[0], 'utf8');
const formatted = JSON.stringify(JSON.parse(jsonStr),
  null, Number(argv.s));
if (argv.r) {
  fs.writeFileSync(argv._[0], formatted);
} else {
  fs.writeFileSync(argv.i, formatted);
}