json_repair: a Python library to repair malformed JSON from LLMs and APIs using heuristics and schema guidance
json_repair: a Python library to repair malformed JSON from LLMs and APIs using heuristics and schema guidance
What it solves
json_repair is designed to handle malformed JSON strings that often occur when receiving data from LLMs, APIs, or logs. It fixes common syntax errors—such as missing quotes, misplaced commas, unclosed brackets, and stray prose—that would normally cause a standard JSON parser like json.loads() to fail.
How it works
The library parses JSON based on a BNF definition and applies heuristics to correct errors. It automatically adds missing parentheses, quotes strings that lack them, and cleans up whitespaces or line breaks. By default, it first attempts a strict parse using the standard library's json.loads() and only falls back to the repair parser if that fails.
Who it’s for
Developers building AI applications that rely on LLM-generated JSON, as well as those processing unreliable data sources like logs or user input where strict JSON compliance is not guaranteed.
Highlights
- Drop-in Replacement: Can be used as a direct replacement for
json.loads()andjson.load(). - Schema-Guided Repair: Supports JSON Schema or Pydantic v2 models to fill missing values, coerce scalars, and drop disallowed properties.
- Streaming Support: Includes a
stream_stablemode to keep partial JSON stable during streaming output. - Strict Mode: Offers a
strict=Trueoption to raise errors on structural issues instead of repairing them. - CLI Tool: Provides a command-line interface for repairing JSON files or piping data via stdin.
Sources
- undefinedmangiucugna/json_repair