Skip to content

JSON Minify — Python source

Remove all whitespace from JSON for the most compact serialization. Validates as it minifies, runs entirely in your browser, with a shareable link to your exact input.

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""json-minify — compact JSON to its smallest valid form.

Language: Python (3.9+, standard library only)
Source:   CosmoDev polyglot showcase port of the JSON Minify tool, mirrored
          from src/lib/json-minify.ts (the canonical TypeScript implementation)
          and cli/json-minify/json-minify.go (the live Go CLI twin).
License:  display source — part of CosmoDev's polyglot tool pages.

Design goals:
  - Pure + deterministic; never raises (invalid JSON -> None).
  - Functionally equivalent to the TS / Go references: same inputs -> same
    outputs.
  - Self-contained: stdlib only (``json`` is part of the language, not a pip
    package).

Behaviour: parse the input, then re-serialize with the item separator ``","``
and key separator ``":"`` so no whitespace survives between tokens. Object key
order is preserved (``dict`` keeps insertion order). ``ensure_ascii=False`` keeps
non-ASCII code points literal, matching the Go twin's ``json.Compact`` and JS's
``JSON.stringify`` (which never emit ``\\uXXXX`` for BMP characters).

Strictness: the ``parse_constant`` hook rejects the non-standard
``Infinity`` / ``-Infinity`` / ``NaN`` tokens that ``json.loads`` otherwise
accepts but Go's ``encoding/json`` rejects, so this port agrees with the Go twin
on every input the canonical test vectors cover.
"""

from __future__ import annotations

import json
from typing import Optional

__all__ = ["minify_json"]


def _reject_constant(value: str) -> object:
    """``parse_constant`` hook: turn NaN / Infinity / -Infinity into a hard
    error so this port matches Go's strict number grammar (those tokens are not
    valid JSON)."""
    raise ValueError(f"non-standard JSON constant: {value!r}")


def minify_json(input: str) -> Optional[str]:
    """Compact JSON serialization of ``input``, or ``None`` if it is not valid
    JSON.

    Mirrors the TS ``minifyJson`` and Go ``Minify``: parse then re-emit with no
    insignificant whitespace. Never raises.
    """
    try:
        decoded = json.loads(input, parse_constant=_reject_constant)
    except (ValueError, RecursionError):
        # ValueError covers JSONDecodeError (and our rejected constants);
        # RecursionError covers pathologically deep nesting.
        return None
    # separators=(",", ":") -> no spaces after ',' or ':'. ensure_ascii=False
    # -> keep non-ASCII literal (matches Go json.Compact / JS JSON.stringify).
    return json.dumps(decoded, separators=(",", ":"), ensure_ascii=False)


# --- showcase (the canonical suite lives in src/lib/json-minify.test.ts) ---
# Run with: python3 src/tool-sources/json-minify/python.py
if __name__ == "__main__":
    def _eq(got, want, label):
        assert got == want, f"{label}: got {got!r}, want {want!r}"

    _eq(minify_json('{\n  "a": 1,\n  "b": [\n    1,\n    2\n  ]\n}'), '{"a":1,"b":[1,2]}', "pretty object")
    _eq(minify_json('{ "x": { "y": [1, 2, 3] } }'), '{"x":{"y":[1,2,3]}}', "nested")
    _eq(minify_json('{"a":1}'), '{"a":1}', "already minified")
    _eq(minify_json("123"), "123", "scalar number")
    _eq(minify_json("true"), "true", "scalar bool")
    _eq(minify_json("null"), "null", "scalar null")
    _eq(minify_json('"héllo 🚀"'), '"héllo 🚀"', "unicode preserved")
    _eq(minify_json("{invalid}"), None, "invalid braces")
    _eq(minify_json(""), None, "empty")
    _eq(minify_json("[1, 2,"), None, "truncated array")

    print("json-minify: showcase OK")

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →