mangiucugna/json_repair

Repair malformed JSON from LLMs, APIs, logs, and user input in Python.

json_repair — Fix Broken JSON in Python

What it is

json_repair is a Python library that takes malformed JSON — the kind that comes out of AI models, APIs, logs, or user input — and fixes it so you can use it as normal JSON. It handles common mistakes like missing quotes, missing commas, unclosed brackets, stray comments, extra prose, and truncated values.

It's designed as a drop-in replacement for Python's built-in json.loads(): you hand it a messy string, it returns a clean Python object.

Quick example

import json_repair

bad_json = '{"users":[{"name":"Ada","role":"admin",}],"ok":true'
# Note: trailing comma, missing closing brace

decoded = json_repair.loads(bad_json)
# Result: {'users': [{'name': 'Ada', 'role': 'admin'}], 'ok': True}

Installation

pip install json-repair

Requires Python 3.10 or newer.

Main functions

Function What it does
json_repair.loads(string) Repairs and decodes a JSON string into a Python object. Drop-in replacement for json.loads().
json_repair.repair_json(string) Returns the repaired JSON as a string (not a Python object).
json_repair.load(file) Repairs and decodes JSON from a file object. Drop-in replacement for json.load().
json_repair.from_file(path) Reads a file and repairs its JSON content.

How it works

The library first tries Python's built-in strict JSON parser. If that succeeds, it returns the result immediately. If it fails, it runs a special "repair parser" that follows the JSON grammar and uses simple heuristics to patch mistakes:

  • Adds missing closing brackets or parentheses when it's clear the structure should be closed
  • Adds missing quotes around keys and values
  • Converts Python-style tuples (like (1, 2)) into JSON arrays
  • Recognizes true/false/null/None case-insensitively
  • Removes comments and stray non-JSON characters
  • Fills in missing values with sensible defaults like empty strings or null

Key options

ensure_ascii=False

By default, non-Latin characters (Chinese, Japanese, Korean, etc.) get converted to \uXXXX escape sequences. Pass ensure_ascii=False to keep them readable:

repair_json("{'test':'统一码'}", ensure_ascii=False)
# Returns: {"test": "统一码"}

skip_json_loads=True

By default, the library first tries Python's strict json.loads(). If you already know the input is invalid, you can skip that check and go straight to the repair parser. This is faster only for known-bad input. Warning: if you force already-valid JSON through the repair parser, it may change the structure or values. So only use this when you're sure the input is broken.

return_objects=True

Makes repair_json() return a Python object directly instead of a JSON string. This is always faster because it avoids serializing the result back to text.

strict=True

Instead of fixing problems, the parser raises a ValueError for structural issues like missing : separators, empty keys/values from stray commas, or multiple top-level elements. This is for when you'd rather fail loudly than guess.

Schema-guided repairs (beta)

You can pass a JSON Schema (or a Pydantic v2 model) to guide the repair process. The parser will then:

  • Fill missing values using defaults, required fields, or first enum values
  • Coerce scalars where safe (e.g., "1" → 1 for integers, "yes" → true for booleans)
  • Drop properties the schema doesn't allow

There are two modes:

  • standard (default): basic schema-guided behavior
  • salvage: more aggressive — drops invalid array items, maps arrays to objects, unwraps single-item arrays, and skips schema-invalid fragments

Requires optional dependencies: pip install 'json-repair[schema]'

stream_stable=True

For streaming scenarios where JSON arrives in pieces, this keeps partial JSON stable between chunks.

Performance notes

  • Default behavior: try strict json.loads() first, repair only if needed — this is the safe path for valid JSON.
  • skip_json_loads=True is not a "faster but equivalent" mode for valid JSON. It's only for input you're certain is broken.
  • The library intentionally does not auto-detect third-party JSON libraries like orjson. If you want orjson semantics, use it yourself and fall back to json_repair only on failure.

Command-line usage

Install with pipx install json-repair, then:

json_repair input.json              # repair a file, print to stdout
json_repair --inline input.json     # overwrite the file in place
json_repair --output out.json input.json
json_repair --strict input.json     # raise errors instead of repairing
json_repair --schema schema.json input.json

If no filename is given, it reads from stdin.

Version pinning

The project uses strict semantic versioning. The README recommends pinning only the major version in requirements.txt:

json_repair==0.*

Why it exists

Large language models (LLMs) often produce JSON that's almost valid — they skip a parenthesis, add extra words, or use single quotes. The author searched for a lightweight Python package to fix this reliably, found none, and wrote one. It's free, maintained as a side project, and accepts contributions.

Limitations

  • Strict mode is not a general-purpose JSON validator — it only catches specific structural issues.
  • Schema-guided repairs are in beta; bugs are expected.
  • The library won't catch IO errors from file operations — you handle those yourself.
  • If the input is extremely broken, repair_json() may return an empty string.

Related

  • Project
  • Project
  • Project
  • Project
  • Project