Python - json without whitespaces
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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.
Output:
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.
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.
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.
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_keysorensure_ascii=Falsewhen needed. - Compact JSON is good for transport and storage, but pretty JSON is better for debugging.
Related reading
- Python - machine learning
- python - prefix sum algorithm
- Python - Single thread executor already being used, would deadlock
- Python - sklearn How to pass parameters to the customize ModelTransformer class by gridsearchcv
- Python - Speed up an A Star Pathfinding Algorithm
- Python - Tree traversal question
- Python - TypeError Object of type 'int64' is not JSON serializable
- python - TypeError unorderable types str float
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.