Tag Archives: python

Indent json strings on the bash

The issue

While I was playing around with CouchDB and cURL I pretty quickly missed a feature to indent the json output string. So after looking around in the Internet for a simple solution I hit simplejson which provides methods to indent a json string.

Get the script

With simplejson I’ve created the following python script:

#!/usr/bin/env python

import sys
import simplejson
import string

content = string.join(sys.stdin.readlines())
json = simplejson.loads(content)
print simplejson.dumps(json, sort_keys=True, indent=2)

What needs to be installed

To be able to run the script simplejson needs to be installed. On a debian based system you can easily run following command to assure simplejson is installed:
sudo apt-get install python-simplejson

How to use it

Let’s store the script to jsonindent.py in a executable path directory such as $HOME/bin (run echo $PATH to get more possible directories). To indent a json script returned for instance from a CouchDB you can easily use following command:
curl -sX GET http://127.0.0.1:5984/example/hello-world | jsonindent.py

The output will look like this:

{
  "_id": "hello-world",
  "_rev": "1-97dd85b06c25328a300f3f4041def370",
  "body": "Well hello and welcome to my new blog...",
  "date": "2009/01/15 15:52:20",
  "title": "Hello World"
}

Looks pretty neat, doesn’t it ;)?