Skip to main content

How to Pretty Print JSON in Python

When working with JSON data in Python, the default output is a compact, single-line format that is efficient for machines but difficult for humans to read. Pretty printing formats JSON with proper indentation, line breaks, and spacing: making it much easier to inspect, debug, and understand complex data structures.

Python's built-in json module provides everything you need to pretty print JSON data from strings, dictionaries, files, and API responses.

Basic Pretty Printing With json.dumps()

The json.dumps() function converts a Python object to a JSON-formatted string. The indent parameter controls the indentation level:

import json

data = {
"name": "Tom",
"age": 28,
"designation": "Software Engineer",
"skills": ["Python", "JavaScript", "SQL"]
}

# Compact format (default)
print(json.dumps(data))

# Pretty printed with 2-space indent
print(json.dumps(data, indent=2))

Output:

{"name": "Tom", "age": 28, "designation": "Software Engineer", "skills": ["Python", "JavaScript", "SQL"]}
{
"name": "Tom",
"age": 28,
"designation": "Software Engineer",
"skills": [
"Python",
"JavaScript",
"SQL"
]
}
note

The indent parameter accepts an integer specifying the number of spaces per indentation level. Common values are 2 and 4.

Pretty Printing a JSON String

When you receive JSON as a string (e.g., from an API), parse it first with json.loads(), then format it with json.dumps():

import json

json_string = '[{"Employee ID":1,"Name":"Tom","Designation":"Software Engineer"},{"Employee ID":2,"Name":"Garima","Designation":"Email Marketing Specialist"}]'

# Parse the JSON string into a Python object
data = json.loads(json_string)

# Pretty print with 2-space indent
print(json.dumps(data, indent=2))

Output:

[
{
"Employee ID": 1,
"Name": "Tom",
"Designation": "Software Engineer"
},
{
"Employee ID": 2,
"Name": "Garima",
"Designation": "Email Marketing Specialist"
}
]

Pretty Printing JSON From a File

To pretty print JSON data stored in a file, load it with json.load() and format with json.dumps():

import json

with open('myfile.json', 'r') as f:
data = json.load(f)

print(json.dumps(data, indent=2))

Output:

{
"emp1": {
"name": "Lisa",
"designation": "programmer",
"age": "34",
"salary": "54000"
},
"emp2": {
"name": "Elis",
"designation": "Trainee",
"age": "24",
"salary": "40000"
}
}
tip

Always use with open(...) context managers when working with files. This ensures the file is properly closed even if an error occurs during processing.

Controlling the Output Format

json.dumps() provides several parameters to customize the output:

Sorting Keys

Use sort_keys=True to sort dictionary keys alphabetically:

import json

data = {"zebra": 1, "apple": 2, "mango": 3}

print(json.dumps(data, indent=2, sort_keys=True))

Output:

{
"apple": 2,
"mango": 3,
"zebra": 1
}

Custom Separators

The separators parameter controls the characters used between items and between keys and values:

import json

data = {"name": "Alice", "age": 30}

# Default separators: (', ', ': ')
print(json.dumps(data, indent=2))

# Compact separators: (',', ':')
print(json.dumps(data, separators=(',', ':')))

Output:

{
"name": "Alice",
"age": 30
}
{"name":"Alice","age":30}

Handling Non-ASCII Characters

Use ensure_ascii=False to preserve Unicode characters instead of escaping them:

import json

data = {"city": "München", "country": "日本"}

# Default: escapes non-ASCII
print(json.dumps(data, indent=2))

# Preserves Unicode characters
print(json.dumps(data, indent=2, ensure_ascii=False))

Output:

{
"city": "M\u00fcnchen",
"country": "\u65e5\u672c"
}
{
"city": "München",
"country": "日本"
}

Parameter Quick Reference

ParameterDescriptionDefaultExample
indentNumber of spaces per indentation levelNone (compact)indent=2
sort_keysSort dictionary keys alphabeticallyFalsesort_keys=True
separatorsCustom item and key-value separators(', ', ': ')separators=(',', ':')
ensure_asciiEscape non-ASCII charactersTrueensure_ascii=False
defaultFunction to handle non-serializable objectsNonedefault=str

Using pprint as an Alternative

Python's pprint module can also format data structures, but it produces Python-specific output (not valid JSON):

import pprint
import json

data = {"name": "Alice", "skills": ["Python", "SQL"], "active": True}

# pprint: Python representation (not JSON)
pprint.pprint(data)

# json.dumps
print(json.dumps(data, indent=2))

Output:

{'active': True, 'name': 'Alice', 'skills': ['Python', 'SQL']}
{
"name": "Alice",
"skills": [
"Python",
"SQL"
],
"active": true
}
pprint vs. json.dumps
  • pprint: Uses single quotes, Python True/False/None: not valid JSON.
  • json.dumps: Uses double quotes, JSON true/false/null: valid JSON.

Always use json.dumps() when you need actual JSON output.

Pretty Printing API Responses

A common use case is formatting JSON responses from web APIs:

import json
import urllib.request

url = "https://jsonplaceholder.typicode.com/users/1"

with urllib.request.urlopen(url) as response:
data = json.loads(response.read())

print(json.dumps(data, indent=2))

Output:

{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}

Saving Pretty Printed JSON to a File

To write formatted JSON to a file, use json.dump() with the indent parameter:

import json

data = {
"employees": [
{"name": "Alice", "role": "Developer"},
{"name": "Bob", "role": "Designer"}
]
}

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

print("Pretty printed JSON saved to output.json")

Command-Line Pretty Printing

Python can pretty print JSON directly from the command line without writing a script:

# Pretty print a JSON file
python -m json.tool myfile.json

# Pretty print piped JSON
echo '{"name":"Alice","age":30}' | python -m json.tool

# With sorting
python -m json.tool --sort-keys myfile.json

Output:

{
"age": 30,
"name": "Alice"
}

Handling Non-Serializable Objects

json.dumps() only handles basic Python types by default. For custom objects, use the default parameter:

import json
from datetime import datetime

data = {
"event": "Launch",
"timestamp": datetime.now()
}

# ❌ Raises TypeError: Object of type datetime is not JSON serializable
# print(json.dumps(data, indent=2))

# ✅ Use default=str to convert non-serializable objects to strings
print(json.dumps(data, indent=2, default=str))

Output:

{
"event": "Launch",
"timestamp": "2024-01-15 14:30:00.123456"
}

Conclusion

Pretty printing JSON in Python is straightforward with the built-in json module.

  • Use json.dumps(data, indent=2) for formatted string output
  • Use json.dump(data, file, indent=2) for writing to files
  • Use python -m json.tool for quick command-line formatting.

Customize the output with sort_keys for alphabetical ordering, ensure_ascii=False for Unicode preservation, and default=str for handling non-serializable objects. Pretty printing is invaluable for debugging, logging, and making JSON data human-readable.