API Navigator Logo

How to Pretty Print JSON in Python

Author: Newtum

This guide demonstrates how to format and display JSON data in a more readable, "pretty" format in Python. This is especially useful for debugging and inspecting API responses.

Using `json.dumps()` with Indentation

The easiest way to pretty-print JSON is to use the `indent` and `sort_keys` arguments of the `json.dumps()` function. `indent` adds newlines and spaces, and `sort_keys` organizes the keys alphabetically.

import json

data = {
    "user": {"name": "Eve", "id": 789},
    "permissions": ["admin", "read", "write"],
    "active": True,
    "settings": {"theme": "dark", "notifications": None}
}

# Use indent=4 for 4-space indentation
# Use sort_keys=True to sort the keys
pretty_json = json.dumps(data, indent=4, sort_keys=True)

print(pretty_json)

Printing a Requests Response Prettily

When you get a JSON response from an API using the `requests` library, you can combine `response.json()` with `json.dumps()` to print it nicely.

import requests
import json

response = requests.get('https://api.github.com/users/google')
if response.status_code == 200:
    # response.json() parses the JSON into a Python dict
    # json.dumps() then formats that dict into a pretty string
    pretty_response = json.dumps(response.json(), indent=2)
    print(pretty_response)
else:
    print(f"Request failed with status code {response.status_code}")