Pass the indent parameter (typically indent=4 or indent=2) to json.dumps() when printing formatted JSON to the console, or to json.dump() when writing formatted JSON directly to a file—optionally pairing it with sort_keys=True and ensure_ascii=False for readable Unicode output.
Basic Example
import json
data = {
"user": "Alice",
"id": 1042,
"roles": ["admin", "editor"],
"location": "Lahore — پاکستان",
"active": True,
}
# 1. Pretty-print formatted JSON to the console
formatted_json = json.dumps(data, indent=4, sort_keys=True, ensure_ascii=False)
print(formatted_json)
# 2. Write formatted JSON directly to a file
with open("config.json", "w", encoding="utf-8") as file:
json.dump(data, file, indent=4, sort_keys=True, ensure_ascii=False)
Console & File Output:
{
"active": true,
"id": 1042,
"location": "Lahore — پاکستان",
"roles": [
"admin",
"editor"
],
"user": "Alice"
}
Key Details & Common Options
json.dumps()vs.json.dump():json.dumps(obj, indent=4)(dump string) serializes a Python object into a formattedstrin memory—use this for console printing, logging, or HTTP payloads.json.dump(obj, file, indent=4)(dump to stream) writes directly to an open file-like object in chunks, avoiding building a huge string in memory first.
- Preserving non-ASCII / Unicode characters (
ensure_ascii=False): By default, Python setsensure_ascii=True, escaping all non-ASCII characters into\uXXXXsequences (e.g.,"پاکستان"becomes"\u067e\u0627..."). Passensure_ascii=Falsealongsideencoding="utf-8"when opening files so international text remains human-readable. - Customizing key-value and item separators (
separators=(",", ": ")): Whenindentis set, Python defaults toseparators=(", ", ": ")(which strips trailing whitespace after commas). You can customize spacing explicitly if needed, or passindent=None, separators=(",", ":")to minify JSON when disk size matters more than readability. - Handling non-serializable objects (
default=str): Standardjson.dump()/json.dumps()raises aTypeErrorondatetime,Path,UUID, orDecimalobjects. Passdefault=str(or a custom serializer function) to convert unsupported types automatically instead of crashing. - Pretty-printing an existing raw JSON string or file from the terminal: If you already have an unformatted
.jsonfile on disk, Python’s built-injson.toolCLI module formats it directly without writing a script:python -m json.tool raw.json formatted.json --indent 4
Summary of Formatting Parameters & Methods
| Method / Parameter | Target Output | Effect | Best Used When |
|---|---|---|---|
json.dumps(obj, indent=4) |
Returns formatted str |
Indents nested objects and arrays by 4 spaces | Printing to console (print()), debugging, or logging. |
json.dump(obj, f, indent=4) |
Writes directly to file f |
Streams formatted JSON to disk without extra memory copy | Saving config files, API snapshots, or large JSON exports. |
sort_keys=True |
Dictionary key order | Sorts dictionary keys alphabetically at every nesting level | Producing deterministic diffs for Git or test comparisons. |
ensure_ascii=False |
Character encoding | Outputs raw UTF-8 characters instead of \uXXXX escapes |
Data containing accented characters, emojis, or non-Latin scripts. |
python -m json.tool |
CLI / stdout / file | Built-in command-line JSON formatter and validator | Quick terminal formatting of raw JSON files or piped curl output. |
You must log in or register to comment.
