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
try:
   import anyjson
except ImportError:
   print >>sys.stderr, "TIP: pip install anyjson"
   raise

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

if __name__ == '__main__':
   sys.exit(run(*sys.argv[1:]))

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

$ chmod +x jsonpprint
David Wilson - 21 November 2010 [«« Reply to this]
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 - 21 November 2010 [«« Reply to this]
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 - 21 November 2010 [«« Reply to this]
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.)

David
Panos Laganakos - 22 November 2010 [«« Reply to this]
Thanks David, this is really handy :)
Ruslan Spivak - 21 November 2010 [«« Reply to this]
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