Thu Jan 15 2026 00:00:00 GMT+0000 (Coordinated Universal Time)
How to format JSON in Python — 3 quick methods
A practical guide to beautifying, minifying and validating JSON using Python's built-in json module. Includes error handling and best practices.
#json#python
JSON is everywhere in modern development — API responses, configuration files, NoSQL databases. Knowing how to format it quickly saves real time when you are debugging.
Method 1: json.dumps with indent
The simplest way to beautify JSON in Python:
import json
raw = '{"name":"Alice","scores":[98,85,92]}'
parsed = json.loads(raw)
print(json.dumps(parsed, indent=2))
Output:
{
"name": "Alice",
"scores": [98, 85, 92]
}
Method 2: Minify with separators
When you need to compress JSON for production payloads:
compact = json.dumps(parsed, separators=(',', ':'))
# {"name":"Alice","scores":[98,85,92]}
The separators argument removes the default whitespace.
Method 3: Validate with try/except
Always wrap JSON parsing in error handling — malformed input is the rule, not the exception:
try:
parsed = json.loads(user_input)
except json.JSONDecodeError as e:
print(f"Invalid JSON at line {e.lineno}, column {e.colno}: {e.msg}")
Best practices
json.loads for strings, json.load for file objectsensure_ascii=False if you have non-ASCII content (CJK, emoji)ijson instead of loading everything into memoryTry it yourself
You can paste your JSON into our JSON Formatter to validate and beautify it instantly — no Python required.