• Home
  • About
    • Richie's Blog photo

      Richie's Blog

      Science, data, biology, digital health, programming, tech

    • Learn More
    • Twitter
    • LinkedIn
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

Pretty Printing JSON (and other data structures)

09 Dec 2014

Reading time ~1 minute

I’ve found the need to print a lot of JSON for recent projects. Examining the contents of a JSON, useful for initial eyeballing of the data, can be tricky as the content and formatting can be quite dense. However, there are a couple of tools that I’ve been using to make this easier.

From within a python script, use the pprint library - useful for printing any data structures:


from pprint import pprint
pprint(json_data, depth=5)

Also, if it’s a JSON string, you can print at the command line using python’s built-in json.tool


$ echo 'some_json_string' | python -m json.tool

# Or, create a shell function, e.g. within the .bashrc file:
function jprint () { echo "$@" | python -m json.tool; }

Sample usage of the function, after reloading the .bashrc file:


$ jprint '{"responseData": {"cursor":{"resultCount":"60","pages":[{"start":"0","label":1},{"start":"4","label":2}],"estimatedResultCount":"60","moreResultsUrl":"http://www.example.com/search?searchterm","searchResultTime":"0.01"}}, "responseDetails": null, "responseStatus": 200}'

{
    "responseData": {
        "cursor": {
            "estimatedResultCount": "60",
            "moreResultsUrl": "http://www.search.com/",
            "pages": [
                {
                    "label": 1,
                    "start": "0"
                },
                {
                    "label": 2,
                    "start": "4"
                }
            ],
            "resultCount": "60",
            "searchResultTime": "0.01"
        }
    },
    "responseDetails": null,
    "responseStatus": 200
}



Like Tweet +1