Pretty print JSON on the command line with Python

I’m often dealing with little bits of JSON, and sometimes it’s helpful to pretty-print them for readability.

Python has a handy tool to make that easy on the command line: json.tool.

E.g.

echo '{"foo": "bar", "thing": { "baz": 42 } }' | python -m json.tool

prints:

{
    "foo": "bar",
    "thing": {
        "baz": 42
    }
}

If you’re on Mac, you can convert JSON in the clipboard to its pretty-printed form with:

pbpaste | python -m json.tool | pbcopy

Ubuntu equivalent with xclip:

xclip -selection clipboard -o | python -m json.tool | tee >(xclip -selection clipboard)

I have that aliased to pcj (for “pretty print clipboard json”).

Mac:

alias pcj='pbpaste | python -m json.tool | pbcopy'

Ubuntu:

alias pcj='xclip -selection clipboard -o | python -m json.tool | tee >(xclip -selection clipboard)'

The three clipboard JSON manipulation aliases I have set up are:

alias jec='xclip -selection clipboard -o | python3 -c "import sys;import json;print(json.dumps(sys.stdin.read().strip()))" | tee >(xclip -selection clipboard)'
alias pcj='xclip -selection clipboard -o | python3 -m json.tool | tee >(xclip -selection clipboard)'
alias mcj='xclip -selection clipboard -o | python3 -c "import sys;import json;print(json.dumps(json.loads(sys.stdin.read()),separators=(\",\",\":\")))" | tee >(xclip -selection clipboard)'

Tech mentioned