Pretty print JSON from the command line

by Ruslan Spivak on October 12, 2010

Recently I’ve worked on a small project where I needed to pretty print JSON from the command line for quick verification.
For the task I created a pp alias in my .bashrc that worked perfectly (all the code is on the same line):

alias pp='python -c "import sys, json; print json.dumps(
json.load(sys.stdin), sort_keys=True, indent=4)"'

Just today I was re-reading the official Python documentation on a json package and came across a small gem – json.tool module that is used for validation and pretty-printing.
I modified my alias which is now way shorter and does the same job as my old one:

alias pp='python -mjson.tool'

And here is pretty-printing in action:

 
pretty-print

If you enjoyed this post why not subscribe via email or my RSS feed and get the latest updates immediately. You can also follow me on GitHub or Twitter.

{ 12 comments… read them below or add one }

Jakub October 13, 2010 at 2:17 AM

Nice tip, thanks!

Reply

Ruslan Spivak October 13, 2010 at 7:10 AM

Hi Jakub,

You’re welcome

Reply

Danny Navarro October 14, 2010 at 4:15 AM

Really handy. Just added it to my .zshrc.

Reply

mark nova April 6, 2011 at 8:00 AM

Just in case somebody need to pretty print json from website: http://www.pretty-print.org

Reply

See Furst July 19, 2011 at 9:32 AM

YOu should mention that you need python version 2.6 or later. 2.3.3 doesn’t have it.

Reply

Me August 5, 2012 at 3:53 PM

Very very nice, this will help me significantly. Thanks for the tips! It’s faster than copying and pasting into an online parser.

Reply

Ruslan Spivak August 5, 2012 at 7:57 PM

You’re welcome

Reply

PShark November 13, 2012 at 12:50 AM

Thanks a lot! Very nice shortcut.

Reply

AC December 7, 2012 at 8:16 PM

Thanks. Great tip. BTW, your alias might collide with ‘pp’ on some machines with PAR packager. Maybe alias to ‘jpp’ or at least recommending checking for collisions?

Reply

Vitaly November 29, 2013 at 11:18 AM

Спасибо за indent=4. Я никак не мог корректно распечатать конфигурационные файл json.

Reply

DutchTraveller December 30, 2013 at 12:12 AM

Great thanks a lot for inline pretty print.

(I use a lot http://www.bodurov.com/JsonFormatter/ for collapsable formatting)

Reply

Anna Belkin November 9, 2014 at 11:52 AM

Hey Ruslan, I made a nice little tool online where you can paste raw JSON and it will pretty print it: http://www.jsonprettyprint.net. I often use it when I am playing around with some APIs and I’m not in a terminal :) What do you think?

Cheers,
Anna

Reply

Speak your mind

{ 1 trackback }

Previous post:

Next post: