nodejs JSON pretty print one-liner

All credit to @danthegoodman on this one, I’m just posting here so I can find it when I need it.

Quoting dan’s comment:

Here’s a oneliner that does the same thing (at least in mac and linux land, not sure about windows):

node -p 'JSON.stringify(JSON.parse(fs.readFileSync(0)),null,2)'

notably, JSON.parse can work off of a buffer and fs.readFileSync(0) reads the zero file descriptor, which is standard input. Then, node -p is a way to execute and log the output from a statement. You could also write it with a node -e 'console.log(...)' if you would rather be in control of when or how the logging happens.

Here’s a snippet that demonstrates it working:

$ echo '{"aaa":123,"bbb":"some string","ccc":["A",1,true],"ddd":{"eee":true}}' \
  | node -p 'JSON.stringify(JSON.parse(fs.readFileSync(0)),null,2)'
{
  "aaa": 123,
  "bbb": "some string",
  "ccc": [
    "A",
    1,
    true
  ],
  "ddd": {
    "eee": true
  }
}

comments powered by Disqus