Last modified: Nov 05, 2024 By Alexander Williams

Python Pretty Print JSON Guide

When working with JSON data in Python, it's often necessary to format it in a readable way. Pretty printing JSON makes it easier to read, debug, and understand the data structure.

Using json.dumps with indent

The simplest way to pretty print JSON is using the json.dumps() method with the indent parameter. This is part of Python's built-in json module.


import json

data = {
    "name": "John Doe",
    "age": 30,
    "cities": ["New York", "London", "Tokyo"],
    "details": {
        "email": "john@example.com",
        "phone": "123-456-7890"
    }
}

formatted_json = json.dumps(data, indent=4)
print(formatted_json)


{
    "name": "John Doe",
    "age": 30,
    "cities": [
        "New York",
        "London",
        "Tokyo"
    ],
    "details": {
        "email": "john@example.com",
        "phone": "123-456-7890"
    }
}

Using pprint for Complex Structures

The pprint module offers more advanced formatting options, especially useful for complex nested structures. It maintains consistent formatting across different data types.


from pprint import pprint

complex_data = {
    "users": [
        {"id": 1, "name": "Alice", "roles": ["admin", "user"]},
        {"id": 2, "name": "Bob", "roles": ["user"]}
    ],
    "settings": {
        "theme": "dark",
        "notifications": True
    }
}

pprint(complex_data)

Customizing JSON Output

When using json.dumps, you can customize the output format using additional parameters. The sort_keys parameter is particularly useful.


formatted_json = json.dumps(data, indent=4, sort_keys=True, ensure_ascii=False)
print(formatted_json)

Pretty Printing to Files

You can also write formatted JSON directly to files, which is useful when working with configuration files or logging.


with open('output.json', 'w') as f:
    json.dump(data, f, indent=4)

Using jq-like Formatting

For more advanced formatting similar to the jq command-line tool, you can combine multiple formatting options:


def pretty_print_json(data):
    print(json.dumps(
        data,
        indent=2,
        sort_keys=True,
        separators=(',', ': '),
        ensure_ascii=False
    ))

pretty_print_json(data)

Error Handling

When pretty printing JSON, it's important to handle potential errors, especially when dealing with invalid JSON data.


try:
    formatted_json = json.dumps(data, indent=4)
except json.JSONDecodeError as e:
    print(f"Error formatting JSON: {e}")

Best Practices

When pretty printing JSON in Python, consider these best practices:

  • Use consistent indentation (4 spaces is standard)
  • Handle Unicode characters properly
  • Consider memory usage for large JSON structures
  • Implement proper error handling

Conclusion

Pretty printing JSON in Python is essential for readability and debugging. Whether using json.dumps() or pprint, choose the method that best fits your needs.

For more complex JSON operations, consider exploring JSON indexing or logging with JSON.