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's profile image 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.

Tags

This post was filed under articles.

This post is part of the series pretty-print-json.

Related Posts

Other posts you may be interested in:

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

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

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.