jsonpprint - a Python script to format JSON data nicely

21 November 2010   5 comments   Python

Powered by Fusion×

This isn't rocket science but it might help someone else.

I often do testing of my various restful HTTP APIs on the command line with curl but often the format the server spits out is very compact and not easy to read. So I pipe it to a little script I've written. Used like this:

$ curl http://worklog/api/events.json?u=1234 | jsonpprint
{'events': [{'allDay': True,
            'end': 1290211200.0,
            'id': '4ce6a2096da6814e5b000000',
            'start': 1290211200.0,
            'title': '@DoneCal test sample'},
           {'allDay': True,
            'end': 1290729600.0,
            'id': '4ce6a22b6da6814e5b000001',

The code is really simple:

#!/usr/bin/env python
import sys
from pprint import pprint
   import anyjson
except ImportError:
   print >>sys.stderr, "TIP: pip install anyjson"

def run(*args):
   if args:
       content = file(args[0]).read()
       content = sys.stdin.read()
   struct = anyjson.deserialize(content)
   return 0

if __name__ == '__main__':

You can download it here Download the file and put it into ~/bin/ and run:

$ chmod +x jsonpprint


David Wilson
Using simplejson + Python2.5 or Python2.6 upwards:

$ curl -s http://twitter.com/users/show/microsoft.json | json
$ type json
json is aliased to `python -m json.tool'
Peter Bengtsson
That's awesome! No need to install a custom script.

It's because of comments like this that I blog. Had I not jotted down my thoughts I wouldn't probably have learned about the simplejson tool.
David Wilson
I found it in the course of writing the exact same script you wrote. :) It's sweet that these things are bundled with a default Python install (along with -m SimpleHTTPServer etc.)

Panos Laganakos
Thanks David, this is really handy :)
Ruslan Spivak
Had the same issue, but originally used 'indent' parameter for json.dumps function: http://ruslanspivak.com/2010/10/12/pretty-print-json-from-the-command-line/

Your email will never ever be published

Related posts

How to book a ticket on the Royal Academy of Music's website 13 November 2010
Welcome to the world: DoneCal.com 22 November 2010
Related by keywords:
Gzip rules the world of optimization, often 09 August 2014
Credit Card formatter in Javascript 19 November 2013
From Postgres to JSON strings 12 November 2013
Migration of Postgres 9.2 to 9.3 with Homebrew and json_enhancements 30 April 2014
To JSON, Pickle or Marshal in Python 08 May 2009
How I made my MongoDB based web app 10 times faster 21 October 2010