You are here

Human-readable json-output with a python one-liner

I was trying to get some metrics from a service that outputs in json and copy-pasted the output into an editor and used a json-plugin to order the output in a human-readable way. While this works fine, I thought it would be easier to write a one-liner that parses the json-output and pretty-prints it on my screen.

That way it would be easier for me to read. Also I can now use grep on the output to search for specific metrics.

The one-liner uses python to read and dump json-output. Here it is:

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

For example, getting the basic version information from jolokia returns this:

$ curl http://localhost:8080/jolokia
{"timestamp":1234567890,"status":200,"request":{"type":"version"},"value":{"protocol":"7.2","config":{"detectorOptions":"{}","canonicalNaming":"true","maxCollectionSize":"0","includeStackTrace":"true","historyMaxEntries":"10","debug":"false","maxDepth":"15","maxObjects":"0","discoveryEnabled":"false","serializeException":"false","agentType":"servlet","debugMaxEntries":"100"},"agent":"1.3.3","info":{"product":"tomcat","vendor":"Apache","version":"7.0.54"}}}

And with the one-liner, it looks like this:

$ curl -s http://localhost:8080/jolokia | python -c "import sys, json; print json.dumps(json.load(sys.stdin), indent=4, sort_keys=True)"
{
    "request": {
        "type": "version"
    },
    "status": 200,
    "timestamp": 1234567890,
    "value": {
        "agent": "1.3.3",
        "config": {
            "agentType": "servlet",
            "canonicalNaming": "true",
            "debug": "false",
            "debugMaxEntries": "100",
            "detectorOptions": "{}",
            "discoveryEnabled": "false",
            "historyMaxEntries": "10",
            "includeStackTrace": "true",
            "maxCollectionSize": "0",
            "maxDepth": "15",
            "maxObjects": "0",
            "serializeException": "false"
        },
        "info": {
            "product": "tomcat",
            "vendor": "Apache",
            "version": "7.0.54"
        },
        "protocol": "7.2"
    }
}

To make it even more easy you could make an alias of it, for example I use the alias 'pj':

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

So now I can pipe the json-output through my 'pj' alias and have a nicely formatted version on my screen. :-)

Edit:
Just found out that there is 'json.tool' as well. So, instead of the above hard-to-read-onliner you can just pipe json data through "python -m json.tool", which is a lot easier to remember. ;-)