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.

Written by Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

Related Posts

Other posts you may be interested in:

Interactions with this post

Interactions with this post

This post has had 0 WebMention interactions, as of Sun, 19 May 2019 21:36:46 +0100.

Have you written a response to this post? Let me know the URL: