Easy CLI JSON Formatting

Command line JSON interpretation can be confusing. Python’s json library (2.6+) provides a simple prettifier:

$ echo '{"json":"obj"}' | python -mjson.tool
{
    "json": "obj"
}

Or facetiously (from the obligatory Internet Chuck Norris Database):

$ curl -s "http://api.icndb.com/jokes/random?firstName=Andrew&lastName=Martin" | python -mjson.tool
{
    "type": "success",
    "value": {
        "categories": [
            "nerdy",
            "chuck norris"
        ],
        "id": 528,
        "joke": "Andrew Martin doesn't use GUI, he prefers COMMAND line."
    }
}

This can be wrapped in a handy shell function:

$ function parse_url_json() 
{
    curl -s "$@" | python -mjson.tool
}

$ parse_url_json 'http://api.icndb.com/jokes/random?firstName=Andrew&lastName=Martin'

2.5 users can install the simplejson library.

Liked this post? Follow this blog to get more. 

  • exhuma

    A short while back, I hammered a small script together which does the same. With syntax highlighting!

    https://github.com/exhuma/braindump/tree/master/jsonformat

    It currently lives in my “sandbox” project, but if people are interested, I could take it out there and make it a real project, so collaboration could be made easier.

    It is by no means perfect. It “works for me”. But I would be willing to work on it a bit more if people are interested.

  • http://lucumr.pocoo.org/ Armin Ronacher

    You might enjoy using our curl wrapper: http://packages.python.org/curlish/ :-)

  • http://www.dmuth.org/ Douglas Muth

    I’m a fan of jsontool, myself: https://github.com/trentm/json

    That said, there’s certainly more than one way to do it. Python people have their way, and us node.js people have it our way. :-)

  • sitaktif

    -mjson does not mean it uses the “mjson” module :/

    Good tip, otherwise!

  • http://www.binarysludge.com Andy

    D’oh! Updated.

  • exhuma

    This looks awesome! And well documented! Thanks :)

  • wjoojoo

    There’s also perl’s json_xs.

  • http://www.dasickis.com/ dasickis

    Check out httpie: https://github.com/jkbr/httpie (written in Python).

  • NorthIsUp

    This isn’t a “node way” vs. “python way” thing, this is a “it ships with the system way” thing. If python is installed, and it is by default on OS X and most Linux distros, then you get python -mjson.tool for free.

    The author doesn’t really explain what is happening, the -m option says ‘run library module as a script’ and the json module has a function called ‘tool’ that takes standard in, and returns formatted json to standard out.

    There are definitely more feature rich tools out there but this one is nice to know for when you are on a stock or foreign system.

  • http://www.dmuth.org/ Douglas Muth

    Ah, I was unclear on that! Yes, something that ships with the system is definitely a big win. i’ll have to remember this technique. :-)