How to Format JSON in Python
Complete guide to pretty-printing, formatting, and sorting JSON in Python using the built-in json module.
Basic JSON Formatting with json.dumps
Python's built-in json module provides everything you need to format JSON.
The indent parameter is the key — it controls how many spaces (or a string like "\t") are used per indentation level.
import json
data = {"name": "Alice", "age": 30, "city": "Paris"}
# 2-space indentation (standard)
print(json.dumps(data, indent=2))
# 4-space indentation
print(json.dumps(data, indent=4))
# Tab indentation
print(json.dumps(data, indent="\t"))
Format a JSON String (parse then format)
import json
json_string = '{"name":"Alice","age":30,"city":"Paris"}'
# Parse then format
data = json.loads(json_string)
formatted = json.dumps(data, indent=2)
print(formatted)
Sort 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
# }
Format a JSON File
import json
# Read and reformat a JSON file
with open('data.json', 'r') as f:
data = json.load(f)
with open('data_formatted.json', 'w') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
Format JSON from the Command Line (Python one-liner)
# Pipe JSON to Python's json.tool module
echo '{"name":"Alice","age":30}' | python3 -m json.tool
# Format a file
python3 -m json.tool data.json
Handle Non-ASCII Characters (Unicode)
import json
data = {"city": "São Paulo", "greeting": "Olá"}
# By default, json.dumps escapes non-ASCII as \uXXXX
# Use ensure_ascii=False to keep Unicode characters readable
print(json.dumps(data, indent=2, ensure_ascii=False))
# Output:
# {
# "city": "São Paulo",
# "greeting": "Olá"
# }
Need to format JSON without writing code?
Paste any JSON into the free online formatter — instant results, no Python environment needed.
Open JSON Formatter →Frequently Asked Questions
What is the difference between json.dumps and json.dump?
json.dumps() returns a formatted string. json.dump() writes directly to a file object. Use dumps for in-memory strings and dump for file output.
How do I pretty print JSON in Python 3?
Use json.dumps(data, indent=2). The indent parameter works in all Python 3 versions. Use print(json.dumps(data, indent=2)) to output to the console.
How do I format a JSON file in-place with Python?
Read with json.load(), then write back with json.dump(data, file, indent=2). Open the file with 'r+' or read then re-open with 'w' to overwrite.