Pretty print JSON in Python

Last Updated on May 13, 2022 by Dave Farquhar

I do a lot of work pulling data from systems via API, then doing things with parts of that data, whether it means feeding it to another system or creating a report. Some of these data structures are huge and unwieldy. Here’s how to pretty print JSON in Python so you can make sense of those data structures and get on with your code–without using an online pretty print website and potentially exposing sensitive data.

While json.loads is the key to getting your JSON data into a Python data structure, there’s a corresponding json.dumps to print it back out. It doesn’t sound like it would pretty print, but that’s what it does.

A code snippet to pretty print JSON in Python

pretty print JSON in Python
You can pretty print JSON in Python using the json.dumps method.

Let’s take a look at some code. I’ll assume you’ve already loaded your libraries, formatted your headers and parameters and all that. I use the requests library when I can, since it’s well understood and works well. I will point out to watch GET vs PUT. When I reuse code from my last script I frequently forget to check which I used last vs what I need this time, and that’s a common source of errors.

response = requests.request("GET", url, headers=headers, params=params)
stats = json.loads(response.text)
print(json.dumps(stats, indent=4, sort_keys=True))

The first line, of course, pulls the data from your API. The second decodes the JSON and loads it into memory so you can work with it. And then of course, the third line prints it back out, but this time not as a mashed-together one-liner you can’t comprehend. You can vary the indent parameter however you prefer. 4 generally works well but sometimes I like to use a smaller value.

But that’s it. Plug this trick into your code, run it, and now you can make sense of that massive JSON data structure and eliminate a lot of trial and error as you try to figure out how to address the element you want.

And if you ever need to do the opposite and build some json based on other variables, be sure to check out f strings in Python for an easy way to do that.

If you found this post informative or helpful, please share it!
%d bloggers like this: