JSON Formatter — Python source
Beautify, minify and validate JSON instantly. Paste, format, copy - all in your browser. Share a link to your exact input.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
#!/usr/bin/env python3
"""JSON formatter — parse, pretty-print (2-space indent), and minify.
Language: Python
CosmoDev polyglot showcase port of the `json-formatter` tool.
Ported from src/tools/JsonFormatter.tsx — display source, part of CosmoDev's
polyglot tool pages.
Parses JSON with json.loads, then re-emits it compact for "minify"
(separators with no whitespace) or indented for "beautify" (indent=2 by
default, matching the island's JSON.stringify(parsed, null, 2)).
ensure_ascii=False matches JavaScript's habit of leaving non-ASCII characters
unescaped. Parse errors raise json.JSONDecodeError, whose string form carries
the message and the line/column position.
Parity caveats versus the TypeScript port: Python preserves float notation
("1.0", "1e3") where JSON.stringify normalizes ("1", "1000"); Python ints are
arbitrary-precision where JS Numbers cap at 2^53, so large integer literals
round-trip unchanged rather than snapping to the nearest double. Object key
order is preserved (dict insertion order, same as JS).
"""
from __future__ import annotations
import json
from dataclasses import dataclass
from typing import Literal, Optional
Mode = Literal["beautify", "minify"]
@dataclass
class FormatResult:
"""Mirrors the TypeScript { output, error } shape."""
output: str
error: Optional[str] = None
def format_json(input: str, mode: Mode = "beautify", indent: int = 2) -> FormatResult:
"""Format a JSON document the way the live island does.
- empty / whitespace-only input -> empty output, no error
- valid JSON + 'minify' -> compact JSON (no whitespace)
- valid JSON + 'beautify' -> indent-space-indented JSON
- invalid JSON -> empty output, error message
"""
raw = input.strip()
if not raw:
return FormatResult(output="", error=None)
try:
parsed = json.loads(raw)
except json.JSONDecodeError as exc:
# str(exc) includes line/column, matching the engine-message feel of
# the island's e.message.
return FormatResult(output="", error=str(exc))
if mode == "minify":
out = json.dumps(parsed, ensure_ascii=False, separators=(",", ":"))
else:
out = json.dumps(parsed, ensure_ascii=False, indent=indent)
return FormatResult(output=out, error=None)
if __name__ == "__main__":
sample = '{"name":"CosmoDev","tools":["json","base64"],"free":true,"nested":{"ok":1}}'
result = format_json(sample, "beautify")
print(result.error if result.error else result.output)
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 →