Developer Documentation
Python
Updated September 19, 2026

Minify JSON in Python

Remove insignificant JSON whitespace safely by parsing and re-serializing in Python.

JSON minification removes insignificant whitespace while preserving the represented data. A parser-based approach is safer than regular expressions because whitespace inside strings must be preserved.

Quick Start#

The following example uses the standard Python API or a widely used package for this task.

Quick start#

Python
1import json23def minify_json(source: str) -> str:4    value = json.loads(source)5    return json.dumps(value, separators=(",", ":"), ensure_ascii=False)67print(minify_json('{"name": "ToolPorta", "active": true}'))

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Minify a file#

Python
1data = json.loads(Path("input.json").read_text(encoding="utf-8"))2Path("minified.json").write_text(3    json.dumps(data, separators=(",", ":"), ensure_ascii=False),4    encoding="utf-8",5)

Important Notes#

The compact separators are (",", ":"); the default encoder otherwise includes spaces after separators.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement JSON Minifier in other languages: