When working with JSON in Python, you often need to format JSON output with proper indentation to make it human-readable. This is essential for debugging, logging, and inspecting API responses.
Python's built-in json module makes pretty printing easy with the indent parameter. You can also use our JSON Formatter tool for quick formatting.
Quick Answer: Use json.dumps(data, indent=2) to pretty print JSON with 2-space indentation in Python.
The Problem: Compact vs Pretty JSON
By default, json.dumps() creates compact JSON on a single line, which is hard to read:
❌ Compact JSON (Hard to Read)
import json
data = {
"name": "Alice",
"age": 30,
"city": "New York",
"hobbies": ["reading", "coding", "hiking"]
}
# Without indentation
compact_json = json.dumps(data)
print(compact_json)
# Output (all on one line):
# {"name": "Alice", "age": 30, "city": "New York", "hobbies": ["reading", "coding", "hiking"]}✅ Pretty Printed JSON (Easy to Read)
import json
data = {
"name": "Alice",
"age": 30,
"city": "New York",
"hobbies": ["reading", "coding", "hiking"]
}
# With indentation
pretty_json = json.dumps(data, indent=2)
print(pretty_json)
# Output (formatted with 2-space indentation):
# {
# "name": "Alice",
# "age": 30,
# "city": "New York",
# "hobbies": [
# "reading",
# "coding",
# "hiking"
# ]
# }The indent=2 parameter adds 2 spaces per indentation level.
Basic Pretty Printing Methods
Method 1: Using json.dumps() with indent
import json
data = {"name": "Bob", "age": 25, "active": True}
# 2-space indentation (most common)
print(json.dumps(data, indent=2))
# 4-space indentation
print(json.dumps(data, indent=4))
# Tab indentation
print(json.dumps(data, indent='\t'))You can use any number for indentation or even a tab character.
Method 2: Using pprint module (for Python objects)
from pprint import pprint
data = {"name": "Charlie", "age": 35, "skills": ["Python", "JavaScript"]}
# Pretty print Python object (not JSON string)
pprint(data)
# Output:
# {'age': 35,
# 'name': 'Charlie',
# 'skills': ['Python', 'JavaScript']}Note: pprint is for Python objects, not JSON strings. Use json.dumps() for JSON.
Pretty Print JSON to Console
Perfect for debugging and development:
Debugging API Responses
import json
import requests
# Fetch data from API
response = requests.get('https://api.example.com/users/1')
data = response.json()
# Pretty print to console for debugging
print(json.dumps(data, indent=2))
# Example output:
# {
# "id": 1,
# "name": "John Doe",
# "email": "[email protected]",
# "address": {
# "street": "123 Main St",
# "city": "Boston"
# }
# }Essential for inspecting API responses during development.
Pretty Print JSON to File
Use json.dump() with indent to save formatted JSON files. For a complete guide, see our Python Write JSON to File tutorial.
Saving Formatted JSON
import json
data = {
"users": [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
],
"total": 2
}
# Write pretty formatted JSON to file
with open('users.json', 'w') as file:
json.dump(data, file, indent=2)
# users.json will contain:
# {
# "users": [
# {
# "id": 1,
# "name": "Alice"
# },
# {
# "id": 2,
# "name": "Bob"
# }
# ],
# "total": 2
# }Creates a readable JSON file perfect for configuration or data storage.
Sorting Keys Alphabetically
Add sort_keys=True to sort keys alphabetically for consistent output:
Before and After Sorting
import json
data = {
"zebra": 1,
"apple": 2,
"mango": 3,
"banana": 4
}
# Without sorting
print(json.dumps(data, indent=2))
# {
# "zebra": 1,
# "apple": 2,
# "mango": 3,
# "banana": 4
# }
# With sorting
print(json.dumps(data, indent=2, sort_keys=True))
# {
# "apple": 2,
# "banana": 4,
# "mango": 3,
# "zebra": 1
# }Sorted keys make JSON output consistent and easier to compare in version control.
Handling Unicode Characters
By default, json.dumps() escapes non-ASCII characters. Use ensure_ascii=False to keep them readable:
Default (Escaped)
import json
data = {"city": "São Paulo", "country": "日本"}
print(json.dumps(data, indent=2))
# Output:
# {
# "city": "S\u00e3o Paulo",
# "country": "\u65e5\u672c"
# }Readable Unicode
import json
data = {"city": "São Paulo", "country": "日本"}
print(json.dumps(data, indent=2, ensure_ascii=False))
# Output:
# {
# "city": "São Paulo",
# "country": "日本"
# }Perfect for international applications with non-English text.
Advanced: Custom Separators
Control the separators between items and key-value pairs:
Custom Formatting
import json
data = {"name": "Alice", "age": 30, "city": "NYC"}
# Default separators
print(json.dumps(data, indent=2))
# {
# "name": "Alice",
# "age": 30,
# "city": "NYC"
# }
# Custom separators (no space after comma)
print(json.dumps(data, indent=2, separators=(',', ': ')))
# Custom separators with extra spacing
print(json.dumps(data, indent=2, separators=(', ', ' = ')))
# {
# "name" = "Alice",
# "age" = 30,
# "city" = "NYC"
# }Real-World Examples
Example 1: Debugging Nested JSON
import json
# Complex nested data
response = {
"status": "success",
"data": {
"user": {
"id": 1,
"profile": {
"name": "Alice",
"settings": {
"theme": "dark",
"notifications": True
}
}
}
}
}
# Pretty print for debugging
print(json.dumps(response, indent=2, sort_keys=True))
# Clear, readable output showing structureExample 2: Logging JSON Data
import json
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
data = {"event": "user_login", "user_id": 123, "timestamp": "2025-01-16"}
# Log pretty printed JSON
logger.info(f"Event data:\n{json.dumps(data, indent=2)}")
# Output in logs will be formatted and readableExample 3: Configuration File
import json
config = {
"database": {
"host": "localhost",
"port": 5432,
"credentials": {
"username": "admin",
"password": "secret"
}
},
"api": {
"rate_limit": 100,
"timeout": 30
}
}
# Save readable configuration
with open('config.json', 'w') as f:
json.dump(config, f, indent=2, sort_keys=True)
print("Config saved in readable format!")Reusable Pretty Print Function
Create a helper function for consistent pretty printing:
Custom Pretty Print Function
import json
def pretty_print_json(data, indent=2, sort_keys=True):
"""
Pretty print JSON data to console
Args:
data: Python dictionary or list to print
indent: Number of spaces for indentation (default: 2)
sort_keys: Whether to sort keys alphabetically (default: True)
"""
print(json.dumps(
data,
indent=indent,
sort_keys=sort_keys,
ensure_ascii=False
))
# Usage
user_data = {"name": "Alice", "age": 30, "city": "São Paulo"}
pretty_print_json(user_data)
# With custom indentation
pretty_print_json(user_data, indent=4)Best Practices
sort_keys=True for version controlensure_ascii=False for international textQuick Reference Cheat Sheet
Basic Pretty Print
json.dumps(data, indent=2)With Sorted Keys
json.dumps(data, indent=2, sort_keys=True)With Unicode Support
json.dumps(data, indent=2, ensure_ascii=False)Complete (All Options)
json.dumps(data, indent=2, sort_keys=True, ensure_ascii=False)To File
json.dump(data, file, indent=2)Helpful Tools
Learn More
Summary
Pretty printing JSON in Python is essential for debugging, logging, and creating readable configuration files. The indent parameter makes it simple.
- •Use
json.dumps(data, indent=2)for basic pretty printing - •Add
sort_keys=Truefor consistent output - •Use
ensure_ascii=Falsefor Unicode characters - •Pretty print in development, compact in production
- •Use
json.dump()for files with same formatting options
Next Steps: Learn how to parse JSON to Python dictionaries or explore our Python Dict to JSON guide.