As a Python developer, I was working on a project where I needed to analyze customer data from an e-commerce API. The JSON responses I received were completely unreadable – everything was put into one line without any formatting, making it hard to read.
This made debugging and data analysis incredibly frustrating. I needed a way to make the JSON output readable and well-formatted.
That’s when I discovered the power of pretty printing JSON in Python. In this article, I’ll share four different methods I’ve used over the years to format JSON data beautifully.
What is Pretty Printing JSON?
Pretty printing JSON means formatting JSON data in a human-readable way with proper indentation, line breaks, and spacing.
Instead of seeing messy, compressed JSON on a single line, you get clean, organized output that’s easy to read and debug.
Method 1 – Use json.dumps() with indent Parameter
This is my go-to method for pretty printing JSON in Python. Python’s json.dumps() function with the indent parameter creates beautifully formatted output.
Let me show you how I used this recently when working with customer order data from a fictional online bookstore:
import json
# Sample customer order data (typical e-commerce scenario)
customer_order = {
"order_id": "ORD-2024-001",
"customer": {
"name": "Sarah Johnson",
"email": "sarah.johnson@email.com",
"address": {
"street": "123 Main Street",
"city": "Austin",
"state": "Texas",
"zip_code": "73301"
}
},
"items": [
{
"product_id": "BOOK-001",
"title": "Python Programming Mastery",
"price": 29.99,
"quantity": 2
},
{
"product_id": "BOOK-002",
"title": "Data Science with Python",
"price": 39.99,
"quantity": 1
}
],
"total_amount": 99.97,
"order_date": "2024-01-15",
"status": "shipped"
}
# Pretty print with 4-space indentation
pretty_json = json.dumps(customer_order, indent=4)
print(pretty_json)Output:
{
"order_id": "ORD-2024-001",
"customer": {
"name": "Sarah Johnson",
"email": "sarah.johnson@email.com",
"address": {
"street": "123 Main Street",
"city": "Austin",
"state": "Texas",
"zip_code": "73301"
}
},
"items": [
{
"product_id": "BOOK-001",
"title": "Python Programming Mastery",
"price": 29.99,
"quantity": 2
},
{
"product_id": "BOOK-002",
"title": "Data Science with Python",
"price": 39.99,
"quantity": 1
}
],
"total_amount": 99.97,
"order_date": "2024-01-15",
"status": "shipped"
}You can see the output in the screenshot below.

The indent=4 parameter adds 4 spaces for each indentation level. You can use any number you prefer – I typically use 2 or 4 spaces depending on the project requirements.
Method 2 – Use json.dumps() with Additional Formatting Options
Sometimes I need more control over the JSON formatting. Python’s json.dumps() function offers several parameters that I find extremely useful.
Here’s how I format JSON data when working with product catalog information:
import json
# Sample product catalog data from a tech store
product_catalog = {
"categories": ["laptops", "smartphones", "tablets"],
"featured_products": [
{
"name": "MacBook Pro 16-inch",
"price": 2399.00,
"specifications": {
"processor": "Apple M3 Pro",
"memory": "18GB RAM",
"storage": "512GB SSD"
},
"in_stock": True,
"reviews": None
},
{
"name": "iPhone 15 Pro",
"price": 999.00,
"specifications": {
"display": "6.1-inch Super Retina XDR",
"storage": "128GB",
"camera": "48MP Main Camera"
},
"in_stock": False,
"reviews": []
}
]
}
# Pretty print with advanced formatting options
formatted_json = json.dumps(
product_catalog,
indent=2, # 2-space indentation
separators=(',', ': '), # Clean separators
sort_keys=True, # Sort dictionary keys alphabetically
ensure_ascii=False # Allow non-ASCII characters
)
print(formatted_json)Output:
{
"categories": [
"laptops",
"smartphones",
"tablets"
],
"featured_products": [
{
"in_stock": true,
"name": "MacBook Pro 16-inch",
"price": 2399.0,
"reviews": null,
"specifications": {
"memory": "18GB RAM",
"processor": "Apple M3 Pro",
"storage": "512GB SSD"
}
},
{
"in_stock": false,
"name": "iPhone 15 Pro",
"price": 999.0,
"reviews": [],
"specifications": {
"camera": "48MP Main Camera",
"display": "6.1-inch Super Retina XDR",
"storage": "128GB"
}
}
]
}You can see the output in the screenshot below.

The sort_keys=True parameter is particularly helpful when I need consistent output for version control or comparing JSON files.
Method 3 – Use the pprint Module
Python’s pprint module is another excellent option for pretty printing JSON data. I often use this when I’m working in interactive Python sessions or debugging.
Here’s how I use pprint when analyzing social media analytics data:
import json
from pprint import pprint
# Sample social media analytics data
social_media_stats = {
"platform": "Instagram",
"account": "@techstartup_austin",
"analytics": {
"followers": 15420,
"following": 892,
"posts": 324,
"engagement_rate": 4.7
},
"recent_posts": [
{
"post_id": "POST_001",
"content": "Just launched our new mobile app! #startup #tech",
"timestamp": "2024-01-15T10:30:00Z",
"metrics": {
"likes": 234,
"comments": 45,
"shares": 12,
"reach": 3400
},
"hashtags": ["startup", "tech", "mobile", "innovation"]
},
{
"post_id": "POST_002",
"content": "Team building day at Lake Travis! #teamwork",
"timestamp": "2024-01-10T14:15:00Z",
"metrics": {
"likes": 187,
"comments": 23,
"shares": 8,
"reach": 2800
},
"hashtags": ["teamwork", "austin", "laketravis"]
}
]
}
# Pretty print using pprint
print("Using pprint:")
pprint(social_media_stats)
# Pretty print with custom width
print("\nUsing pprint with custom width:")
pprint(social_media_stats, width=60)Output:
Using pprint:
{'account': '@techstartup_austin',
'analytics': {'engagement_rate': 4.7,
'followers': 15420,
'following': 892,
'posts': 324},
'platform': 'Instagram',
'recent_posts': [{'content': 'Just launched our new mobile app! #startup #tech',
'hashtags': ['startup', 'tech', 'mobile', 'innovation'],
'metrics': {'comments': 45,
'likes': 234,
'reach': 3400,
'shares': 12},
'post_id': 'POST_001',
'timestamp': '2024-01-15T10:30:00Z'},
{'content': 'Team building day at Lake Travis! #teamwork',
'hashtags': ['teamwork', 'austin', 'laketravis'],
'metrics': {'comments': 23,
'likes': 187,
'reach': 2800,
'shares': 8},
'post_id': 'POST_002',
'timestamp': '2024-01-10T14:15:00Z'}]}You can see the output in the screenshot below.

The pprint module automatically handles the formatting and is especially useful when working with Python dictionaries that represent JSON-like data.
Method 4 – Read and Pretty Printing JSON from Files
In real-world scenarios, I often need to read JSON data from files and then pretty-print it. This is especially common when working with configuration files or API response logs.
Here’s how I handle JSON files containing restaurant review data:
import json
# First, let's create a sample JSON file
restaurant_data = {
"restaurant_id": "REST_001",
"name": "Austin BBQ House",
"location": {
"address": "456 South Lamar Blvd",
"city": "Austin",
"state": "Texas",
"zip_code": "78704"
},
"cuisine_type": "BBQ",
"rating": 4.8,
"price_range": "$$",
"menu_highlights": [
{
"item": "Brisket Plate",
"price": 18.99,
"description": "Slow-smoked beef brisket with sides"
},
{
"item": "Pulled Pork Sandwich",
"price": 12.99,
"description": "House-smoked pulled pork with coleslaw"
}
],
"reviews": [
{
"reviewer": "Mike Thompson",
"rating": 5,
"comment": "Best BBQ in Austin! The brisket melts in your mouth.",
"date": "2024-01-12"
},
{
"reviewer": "Jennifer Davis",
"rating": 4,
"comment": "Great food, but the wait time was a bit long.",
"date": "2024-01-08"
}
]
}
# Write to JSON file
with open('restaurant_data.json', 'w') as file:
json.dump(restaurant_data, file)
# Read and pretty print from file
def pretty_print_json_file(filename):
try:
with open(filename, 'r') as file:
data = json.load(file)
# Pretty print the loaded data
pretty_json = json.dumps(data, indent=3, sort_keys=True)
print(pretty_json)
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
except json.JSONDecodeError:
print(f"Error: Invalid JSON in file '{filename}'.")
# Pretty print the restaurant data from file
# Pretty print the restaurant data from file
print("Restaurant data from JSON file:")
pretty_print_json_file('restaurant_data.json')Output:
{
"cuisine_type": "BBQ",
"location": {
"address": "456 South Lamar Blvd",
"city": "Austin",
"state": "Texas",
"zip_code": "78704"
},
"menu_highlights": [
{
"description": "Slow-smoked beef brisket with sides",
"item": "Brisket Plate",
"price": 18.99
},
{
"description": "House-smoked pulled pork with coleslaw",
"item": "Pulled Pork Sandwich",
"price": 12.99
}
],
"name": "Austin BBQ House",
"price_range": "$$",
"rating": 4.8,
"restaurant_id": "REST_001",
"reviews": [
{
"comment": "Best BBQ in Austin! The brisket melts in your mouth.",
"date": "2024-01-12",
"rating": 5,
"reviewer": "Mike Thompson"
},
{
"comment": "Great food, but the wait time was a bit long.",
"date": "2024-01-08",
"rating": 4,
"reviewer": "Jennifer Davis"
}
]
}
This method is incredibly useful when I need to quickly examine large JSON configuration files or API response logs stored on disk.
When to Use Each Method
Based on my experience, here’s when I use each method:
json.dumps() with indent: My default choice for most scenarios. It’s fast, reliable, and gives clean output.
json.dumps() with advanced options: When I need sorted keys, custom separators, or special character handling.
pprint module: Great for interactive debugging sessions and when working with Python dictionaries.
File operations: Essential when working with large datasets or when I need to save formatted output.
Custom functions: When I need additional features like error handling, timestamping, or special formatting rules.
Working with JSON data has been a constant part of my development journey for over a decade. From debugging API responses to analyzing complex data structures, pretty printing JSON has saved me countless hours and made my code much more maintainable.
The methods I’ve shared in this article cover virtually every scenario you’ll encounter – from simple formatting needs to complex enterprise applications with massive datasets. The key is understanding when to use each approach and always handling edge cases gracefully.
You may also read:
- Happy Birthday: Code in Python
- end in Python
- Find the Area of a Square in Python
- Save Images in Python

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.