Pretty-printing JSON in the terminal

by Kasper Tidemann

If you’re reading this, chances are you’ve probably worked with JSON in the terminal before. A very common use-case is when dealing with NoSQL databases such as MongoDB or Riak. curl‘ing the database for a resource spits out JSON like so:

curl -X GET http://localhost:8098/riak/users?keys=true

{"props":{"name":"users","allow_mult":false,"basic_quorum":false,"big_vclock":50,"chash_keyfun":{"mod":"riak_core_util","fun":"chash_std_keyfun"},"dw":"quorum","last_write_wins":false,"linkfun":{"mod":"riak_kv_wm_link_walker","fun":"mapreduce_linkfun"},"n_val":3,"notfound_ok":true,"old_vclock":86400,"postcommit":[],"pr":0,"precommit":[],"pw":0,"r":"quorum","rw":"quorum","small_vclock":50,"w":"quorum","young_vclock":20},"keys":["kt@meemo.io","cl@meemo.io"]}

Unfortunately, that’s not too easily readable. This brings us to the fine art of making JSON look good in the terminal, also known as JSON pretty-printing. Jeff Hodges has whipped up a great, little tool for doing just that named jsonpp.

Install it using your favorite package manager – brew install jsonpp, for instance – and pipe the result into jsonpp as follows:

curl -X GET http://localhost:8098/riak/users?keys=true | jsonpp

{
  "props": {
    "name": "users",
    "allow_mult": false,
    "basic_quorum": false,
    "big_vclock": 50,
    "chash_keyfun": {
      "mod": "riak_core_util",
      "fun": "chash_std_keyfun"
    },
    "dw": "quorum",
    "last_write_wins": false,
    "linkfun": {
      "mod": "riak_kv_wm_link_walker",
      "fun": "mapreduce_linkfun"
    },
    "n_val": 3,
    "notfound_ok": true,
    "old_vclock": 86400,
    "postcommit": [],
    "pr": 0,
    "precommit": [],
    "pw": 0,
    "r": "quorum",
    "rw": "quorum",
    "small_vclock": 50,
    "w": "quorum",
    "young_vclock": 20
  },
  "keys": [
    "kt@meemo.io",
    "cl@meemo.io"
  ]
}

Now, that looks way better.