Pretty Printing JSON using Node.JS on the Command Line
I've previously written about using Python to pretty print JSON and an alternative using Ruby, but another I've not yet spoke about is using Node.JS.
As we saw in Converting X.509 and PKCS#8 .pem
file to a JWKS (in Node.JS), we can use JSON.stringify
with an argument to denote how to pretty-print the JSON:
const json = {
wibble: 'bar'
};
console.log(JSON.stringify(json, null, 4));
However, we can turn this into a handy one-liner with the help of the node
executable:
node -r fs -e 'console.log(JSON.stringify(JSON.parse(fs.readFileSync("/dev/stdin", "utf-8")), null, 4));'
This will take in data from stdin
, and then output a pretty-printed JSON object! Note that we need to JSON.parse
the result from stdin
as it will be a String, not a JSON object.