Last Updated: September 29, 2021
·
6.979K
· oleiade

Zsh function to pretty print json in shell

I found Luis Nell trick to easily pretty print json in shell or code editor very usefull, so I decided to port it into my zsh config as a function.

As it might be usefull to someone else, here's the code. Might be compatible with bash and other shells with a few adjustements.

function pjson {
    if [ $# -gt 0 ];
        then
        for arg in $@
        do
            if [ -f $arg ];
                then
                less $arg | python -m json.tool
            else
                echo "$arg" | python -m json.tool
            fi
        done
    fi
}

It can whether print from a string cmdline arg or a file, and arguments can be mixed.

pjson '{"test": "test"}'
or
pjson myjsonfile.json
or even
pjson '{"test": "test"}' myjsonfile.json will work.

3 Responses
Add your response

Shameless self promotion ahead

I hacked a simple nodejs module for doing precisely that https://github.com/tralamazza/prettyson

over 1 year ago ·

Nifty one. Definitely love it.

over 1 year ago ·

Thanks for sharing!

over 1 year ago ·