Ruslan's Blog Ruslan's Blog
Pretty print JSON from the command line

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:


arrow11 Responses

  1. Jakub
    47 mos, 1 wk ago

    Nice tip, thanks!

  2. Ruslan Spivak
    47 mos, 1 wk ago

    Hi Jakub,

    You’re welcome

  3. 47 mos ago

    Really handy. Just added it to my .zshrc.

  4. mark nova
    41 mos, 1 wk ago

    Just in case somebody need to pretty print json from website:

  5. See Furst
    37 mos, 4 wks ago

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

  6. Me
    25 mos ago

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

  7. Ruslan Spivak
    25 mos ago

    You’re welcome

  8. PShark
    21 mos, 3 wks ago

    Thanks a lot! Very nice shortcut.

  9. AC
    21 mos ago

    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?

  10. Vitaly
    9 mos ago

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

  11. DutchTraveller
    8 mos ago

    Great thanks a lot for inline pretty print.

    (I use a lot for collapsable formatting)

Leave A Comment