Developer Documentation
Python
Updated September 19, 2026

Format JSON in Python

Pretty-print JSON with predictable indentation and validation in Python.

Formatting JSON means parsing valid JSON and serializing it again with whitespace and indentation that make the structure easier to read. Parsing first also catches malformed input.

Quick Start#

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

Quick start#

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

Common Operations#

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

Format a file#

Python
1from pathlib import Path2import json34source = Path("input.json").read_text(encoding="utf-8")5data = json.loads(source)6Path("formatted.json").write_text(7    json.dumps(data, indent=, ensure_ascii=False) + "\n",8    encoding="utf-8",9)

Important Notes#

Use ensure_ascii=False when you want readable Unicode output rather than \uXXXX escape sequences.

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 Formatter in other languages: