Python
JSON
data serialization
whitespace removal
programming tips

Python - json without whitespaces

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

If you want compact JSON in Python, the usual answer is json.dumps(..., separators=(",", ":")). The default encoder inserts spaces after commas and colons for readability, but those spaces are optional in JSON syntax. Removing them is useful when you are generating payloads for APIs, cache keys, logs, or compact files.

Use json.dumps With Compact Separators

Python's json module already knows how to emit valid JSON without extra spaces. The important option is the separators argument.

python
1import json
2
3payload = {
4    "name": "Ada",
5    "active": True,
6    "scores": [10, 20, 30],
7}
8
9pretty = json.dumps(payload)
10compact = json.dumps(payload, separators=(",", ":"))
11
12print(pretty)
13print(compact)

Output:

text
{"name": "Ada", "active": true, "scores": [10, 20, 30]}
{"name":"Ada","active":true,"scores":[10,20,30]}

That is usually the right solution. It keeps the JSON valid and removes whitespace only where JSON grammar allows it.

Write Compact JSON to a File

If you are writing directly to disk, use json.dump with the same separators.

python
1import json
2from pathlib import Path
3
4payload = {
5    "id": 42,
6    "tags": ["python", "json"],
7    "enabled": False,
8}
9
10path = Path("compact.json")
11with path.open("w", encoding="utf-8") as f:
12    json.dump(payload, f, separators=(",", ":"))
13
14print(path.read_text(encoding="utf-8"))

This produces a single-line JSON file with no unnecessary spaces. If you also want a trailing newline for command-line tools, write one explicitly after dump finishes.

Do Not Strip Spaces With String Replacement

A common mistake is to serialize JSON normally and then call replace(" ", ""). That breaks valid data because spaces inside string values are real content, not formatting.

python
1import json
2
3payload = {"message": "hello world", "count": 1}
4wrong = json.dumps(payload).replace(" ", "")
5right = json.dumps(payload, separators=(",", ":"))
6
7print(wrong)
8print(right)

The first result turns "hello world" into "helloworld", which changes the meaning of the data. The second result removes only structural whitespace.

Other Options That Matter

Compact output is often used together with a few other encoder options.

ensure_ascii=False keeps Unicode characters readable instead of escaping them. sort_keys=True gives deterministic key order, which helps when comparing outputs in tests or generating signatures. These options are independent from whitespace control.

python
1import json
2
3payload = {"city": "Montréal", "b": 2, "a": 1}
4encoded = json.dumps(
5    payload,
6    separators=(",", ":"),
7    ensure_ascii=False,
8    sort_keys=True,
9)
10
11print(encoded)

That produces compact JSON while still being stable and human-checkable.

When Compact JSON Is Worth It

For small payloads, the size difference is minor. For large collections or repeated messages, compact encoding can noticeably reduce transfer size and log volume. It is also useful when JSON becomes part of another protocol that expects dense text, such as signed tokens, message queues, or cache serialization.

That said, compact JSON is worse for manual debugging. Pretty-printed JSON with indentation is easier to inspect during development. It is normal to use pretty output locally and compact output in production paths.

Common Pitfalls

The biggest mistake is manually stripping spaces from the serialized string. That can corrupt spaces inside JSON string values.

Another issue is assuming compact JSON means minified in every possible way. The encoder removes optional spaces, but it still preserves the data exactly as required by JSON rules.

Developers also sometimes mix indent with compact separators and expect one-line output. indent asks the encoder to pretty-print, so it works against the goal of dense output.

Finally, remember that compact JSON does not compress repeated keys or large values. If payload size is still a problem, compression such as gzip may matter more than whitespace removal.

Summary

  • Use json.dumps(..., separators=(",", ":")) for compact JSON strings.
  • Use json.dump(..., separators=(",", ":")) for compact JSON files.
  • Do not remove spaces with string replacement.
  • Combine compact separators with sort_keys or ensure_ascii=False when needed.
  • Compact JSON is good for transport and storage, but pretty JSON is better for debugging.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.