Parsing JSON from command line using Python

Frederic Cambus February 04, 2014 [Command Line]

With JSON becoming ubiquitous as an API response format, it is sometimes desirable to parse JSON data from command line. There are multiple tools available in order to do so, and I'm personally using jq, a lightweight and flexible command-line JSON processor. While jq is a fantastic tool, it introduces a dependency and might not be available in all environments.

Python, on the other end, comes preinstalled on most Linux distributions and supports JSON out of the box since version 2.6. It can be used to pretty print or parse data, here are a few examples:

Pretty printing JSON data:

curl -s http://www.telize.com/geoip/46.19.37.108 | python -mjson.tool
{
    "area_code": "0",
    "asn": "AS196752",
    "continent_code": "EU",
    "country": "Netherlands",
    "country_code": "NL",
    "country_code3": "NLD",
    "dma_code": "0",
    "ip": "46.19.37.108",
    "isp": "Tilaa V.O.F.",
    "latitude": 52.5,
    "longitude": 5.75,
    "timezone": "Europe/Amsterdam"
}

A one-liner for parsing simple JSON data:

curl -s http://www.telize.com/geoip/46.19.37.108 | python -c 'import sys, json; print json.load(sys.stdin)["country"]'
Netherlands

A one-liner for parsing JSON arrays:

curl -s http://api.statdns.com/x/46.19.37.108 | python -c 'import sys, json; print json.load(sys.stdin)["answer"][0]["rdata"]'
statdns.net.