← til

Pretty formatting JSON

January 21, 2019
bash

I've used to use some silly NPM package for pretty formatting of JSON before.

It came with the json executable so I would just pipe the output of cat to it and it would give me the pretty printed json.

Let's say we have this ugliness saved in ugly.json:

{"foo":"bar","wat":"lol","user":{"name":"Bugs Bunny","address":{"street":"underground street","city":"acme town"}}}

I've used this command to pretty print it before:

cat ugly.json | json

Which outputs:

{
  "wat" : "lol",
  "foo" : "bar",
  "user" : {
    "address" : {
      "street" : "underground street",
      "city" : "acme town"
    },
    "name" : "Bugs Bunny"
  }
}

In the meantime I've changed my global node version, so that executable is not available anymore.

Luckily, I've found out that I don't need the NPM package at all. There's a Linux command that does this:

cat ugly.json | json_pp

Which outputs the same pretty formated JSON:

{
  "wat" : "lol",
  "foo" : "bar",
  "user" : {
    "address" : {
      "street" : "underground street",
      "city" : "acme town"
    },
    "name" : "Bugs Bunny"
  }
}

I took it even further for my use case and directly copied the pretty JSON into clipboard which I then shared with someone:

cat ugly.json | json_pp | pbcopy

pbcopy is OSX command for copying text to clipboard, use xclip -sel clip on Linux.