TATECHATLAS
◎ English
Programming / Guide

Mastering JSON Output Formatting in Python

Learn how to control JSON serialization using separators, indentation, key sorting, and ASCII encoding to optimize for machine or human readability.

On this page

To control the output format of the json.dumps function in Python, you must use four specific keyword arguments: separators, indent, sort_keys, and ensure_ascii. These parameters allow you to switch between a compact format suitable for network transmission and a pretty-printed format for human debugging. For example, using separators=(',', ':') removes all unnecessary whitespace, while indent=4 adds structural spacing. To ensure consistent output for version control or hashing, use sort_keys=True to order dictionary keys alphabetically. Finally, use ensure_ascii=False to preserve non-ASCII characters like emojis or Cyrillic text instead of escaping them into Unicode sequences.

Format Output as a Serialization Contract

When designing an API or a configuration system, the format of your JSON output is part of the contract between your system and its consumer. You must decide whether the output is intended for a machine or a human.

Machine-to-machine communication favors compactness to save bandwidth and processing time. Human-to-machine communication (like configuration files) favors readability and ease of debugging. Python's json.dumps provides the tools to satisfy both requirements through a specific set of formatting parameters.

When writing JSON to a file, remember that json.dump writes strings. If you use ensure_ascii=False, ensure your file object is opened with the correct encoding (e.g., encoding='utf-8') to prevent errors.

separators: Compact Encoding for Machine Exchange

By default, Python's json.dumps adds a space after commas and colons (', ', ': ') to make the output readable. While helpful for humans, these extra bytes add up in large datasets.

The separators parameter accepts a tuple containing the item separator and the key separator. To achieve the most compact JSON representation, use (',', ':'). This eliminates all whitespace between elements, making the payload as small as possible for network transmission.

import json

data = [1, 2, 3, {'a': 5, 'b': 7}]
# Default output: '[1, 2, 3, {"a": 5, "b": 7}]'
# Compact output:
compact_json = json.dumps(data, separators=(',', ':'))
print(compact_json)
# Output: [1,2,3,{"a":5,"b":7}]

indent: Readability for Humans and Debugging

When you need to inspect a JSON structure, use the indent parameter. It accepts an integer representing the number of spaces per indentation level, or a string like '\t' for tabs.

A critical nuance is that when indent is not None, the default separators change from (', ', ': ') to (',', ': '). This ensures that the structure remains clean without unnecessary trailing spaces on lines. This behavior was introduced in Python 3.4.

import json

data = {'id': 1, 'meta': {'type': 'test', 'active': True}}
# Pretty-printed with 4 spaces
pretty_json = json.dumps(data, indent=4)
print(pretty_json)
# Output:
# {
#     "id": 1,
#     "meta": {
#         "type": "test",
#         "active": true
#     }
# }

sort_keys: Deterministic Key Order

In Python, dictionaries are ordered by insertion since 3.7, but for serialization, you often need a guaranteed, deterministic order to ensure that two identical dictionaries always produce the exact same string. This is vital for generating checksums or comparing files in Git.

Setting sort_keys=True will sort the dictionary keys alphabetically. Note that this sorting happens before keys are converted to strings; therefore, numeric keys are sorted by their actual value (e.g., 2 comes before 10) rather than their string representation ('10' before '2').

import json

data = {'z': 1, 'a': 10, 'm': 5}
# Without sorting, order depends on insertion
unsorted = json.dumps(data)
# With sorting, order is guaranteed
sorted_json = json.dumps(data, sort_keys=True)
print(sorted_json)
# Output: {"a": 10, "m": 5, "z": 1}

ensure_ascii: Handling Non-ASCII Characters

By default, json.dumps uses ensure_ascii=True, which escapes all non-ASCII characters into Unicode escape sequences (e.g., \u1234). This ensures the output is safe for environments that only support 7-bit ASCII.

If you set ensure_ascii=False, the characters are output as-is, except for the quotation mark, reverse solidus, and control characters U+0000 through U+001F, which are always escaped per the JSON specification. This makes the JSON much more readable for humans when dealing with languages like Russian, Chinese, or emojis, but it requires the receiving system to handle the correct encoding (usually UTF-8).

import json

data = {"greeting": "Привет", "emoji": "🚀"}
# Default (escaped):
print(json.dumps(data))
# Output: {"greeting": "\u041f\u0440\u0438\u0432\u0435\u0442", "emoji": "\ud83d\ude80"}

# Unescaped:
print(json.dumps(data, ensure_ascii=False))
# Output: {"greeting": "Привет", "emoji": "🚀"}

Combining Parameters: Common Output Profiles

You can combine these parameters to create specific output profiles. For a configuration file intended for version control, use indent=4 and sort_keys=True to ensure clean, readable, and stable diffs.

For a high-performance API response, use separators=(',', ':') and ensure_ascii=True to minimize payload size and maximize compatibility. The Python CLI tool python -m json also supports these via --sort-keys, --indent, --tab, --compact, and --no-ensure-ascii.

# Profile: Configuration File (Human Readable)
config = {'version': 1.0, 'features': ['auth', 'logs'], 'debug': False}
print(json.dumps(config, indent=2, sort_keys=True))

# Profile: API Payload (Machine Optimized)
print(json.dumps(config, separators=(',', ':'), ensure_ascii=True))

Interaction with File Encoding

A common mistake occurs when writing JSON to a file using json.dump(). The json module always produces a Python string (str), not a bytes object. Therefore, the file object must support string input.

If you use ensure_ascii=False to write literal non-ASCII characters, you must explicitly specify the encoding when opening the file. If you do not, the system will use the platform's default encoding, which may lead to errors or corrupted characters on different operating systems.

import json

data = {"name": "Иван"}

# Correct way to write non-ASCII to a file
with open("data.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False)

Decision Criteria: Choosing the Right Format

Choosing a format involves balancing three trade-offs: size, readability, and stability. Compact formats (separators) reduce byte counts but make manual inspection and Git diffs difficult. Pretty-printing (indent) improves readability but increases file size significantly.

Use sort_keys=True whenever you need to compare JSON objects or use them as keys in a hash-based system. Use ensure_ascii=False when the data is primarily for human consumption in a UTF-8 environment, but stick to True for maximum compatibility in legacy systems or strictly ASCII protocols.

# Summary Table Logic:
# 1. Network/API -> separators=(',', ':'), ensure_ascii=True
# 2. Config/Logs -> indent=4, sort_keys=True, ensure_ascii=False
# 3. Debugging -> indent=4, ensure_ascii=False

Things to check

  • Check if separators is a tuple of two strings.
  • Check if indent is an integer or string.
  • Check if sort_keys is a boolean.
  • Check if ensure_ascii is a boolean.
  • Check if the output is a string.

This guide covers output formatting parameters only; it does not address input validation, custom object encoders (default parameter), or circular reference detection. Note that sort_keys guarantees deterministic order for dictionary keys at each level but does not impose ordering on list elements or other non-dict containers. The indent parameter behavior changed in Python 3.4, where providing an indent value also changes the default separators to (',', ': ').

Sources

  1. Python: json ↗
  2. Python: pathlib ↗
Back to top ↑