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

Comments

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.)

David

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.

Previous:
How to book a ticket on the Royal Academy of Music's website November 13, 2010 Web development
Next:
Welcome to the world: DoneCal.com November 22, 2010 Python, Tornado
Related by category:
How I run standalone Python in 2025 January 14, 2025 Python
get in JavaScript is the same as property in Python February 13, 2025 Python
How to resolve a git conflict in poetry.lock February 7, 2020 Python
Best practice with retries with requests April 19, 2017 Python
Related by keyword:
Msgpack vs JSON (with gzip) December 19, 2017 Python, Web development
How do you thousands-comma AND whitespace format a f-string in Python March 17, 2024 Python
How slow is Node to Brotli decompress a file compared to not having to decompress? January 19, 2024 Linux, Node, macOS
Format thousands in Python February 1, 2019 Python