mangiucugna/json_repair

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

What it solves

json_repair is designed to handle malformed JSON strings that often result from LLM outputs, APIs, logs, or user input. 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 structural issues. It automatically adds missing parentheses, quotes strings that are missing quotation marks, and cleans up whitespaces and line breaks. By default, it first attempts a strict json.loads() check; if that fails, it falls back to its own repair parser to salvage the data.

Who it’s for

Developers building applications that rely on structured data from non-deterministic sources, particularly those integrating LLMs that may produce slightly invalid JSON.

Highlights

  • Drop-in Replacement: Can be used as a direct replacement for json.loads() and json.load().
  • Schema-Guided Repair: Supports using JSON Schema or Pydantic v2 models to fill missing values, coerce types, and drop disallowed properties.
  • Streaming Support: Includes a stream_stable mode to keep partial JSON stable while data is being streamed.
  • Strict Mode: Offers a strict=True option 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.

Related

  • Project
  • Project
  • Dispatch
  • Project
  • Project