Format and minify JSON safely
Pretty-print for people, minify for compact transport, and validate before doing either.
Format JSON for reading
Formatting adds indentation and line breaks without changing the data. It is useful when inspecting API responses, configuration files, or nested objects in a debugger.
import json
text = '{"name":"Ada","active":true,"message":"hello world"}'
value = json.loads(text)
pretty = json.dumps(value, indent=2, ensure_ascii=False)
print(pretty)The output has line breaks and indentation, but the value of message remains "hello world".
Minify JSON for compact output
Minification removes insignificant whitespace. It can reduce the size of a JSON payload, but it does not compress data and it makes manual inspection harder.
compact = json.dumps(value, separators=(",", ":"), ensure_ascii=False)
print(compact)
# {"name":"Ada","active":true,"message":"hello world"}
assert json.loads(pretty) == json.loads(compact)| Situation | Better choice |
|---|---|
| Reviewing a config file | Format with indentation |
| Sending a compact API payload | Minify after parsing |
| Large repeated data | Consider transport compression separately |
Validate before changing whitespace
Do not remove spaces with a generic text replacement. Spaces inside quoted strings are data. Parse the JSON first, then serialize it again with the format you need. A parsing error means the source is not valid JSON and should be fixed before formatting.
try:
json.loads('{"name": Ada}')
except json.JSONDecodeError as exc:
print(f"Invalid JSON at line {exc.lineno}, column {exc.colno}")Fix the unquoted Ada in the source before formatting. A formatter cannot safely guess whether it was meant to be a string or another value.