Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Heuristic:666ghj BettaFish JSON Output Repair

From Leeroopedia
Knowledge Sources
Domains Debugging, LLMs, Optimization
Last Updated 2026-10-08 21:30 GMT

Overview

Robust JSON extraction and repair from LLM outputs that may contain markdown fences, trailing commas, or truncated content.

Description

LLMs frequently produce JSON with errors: wrapping in markdown code fences (` ```json `), adding trailing commas, truncating long outputs, or mixing JSON with prose. The `json-repair` library (pinned to 0.53.0) is used as the primary repair tool, with multi-attempt parsing fallback. The system extracts JSON from mixed-text responses by scanning for `{...}` or `[...]` patterns, then attempts repair before failing. Chapter generation stores failed JSON blocks to a logging directory for post-hoc analysis.

Usage

Use this heuristic when parsing LLM-generated JSON that may be malformed, truncated, or wrapped in markdown. It is critical for report structure generation, search query generation, and any structured output from LLMs.

The Insight (Rule of Thumb)

  • Action: Use `json_repair.repairs()` as the primary parser for LLM JSON output. Fall back to regex-based extraction if repair fails.
  • Value: `json-repair==0.53.0` pinned in requirements. Max retry attempts: `CHAPTER_JSON_MAX_ATTEMPTS=2`.
  • Trade-off: Repair may produce slightly different JSON than intended, but is far more robust than strict `json.loads()`.
  • Compatibility: Works with any LLM output containing JSON. Unrepairable blocks are logged to `logs/json_repair_failures/`.

Reasoning

LLM JSON output failure rates can be 5-15% depending on model, prompt length, and output complexity. Common failure modes include: (1) markdown code fences around JSON, (2) trailing commas in arrays/objects, (3) truncated JSON due to token limits, (4) explanatory text mixed with JSON. The `json-repair` library handles most of these by being more permissive than standard JSON parsers. Multi-attempt parsing provides a second chance for transient failures.

Code Evidence

JSON repair library dependency from `requirements.txt:81`:

json-repair==0.53.0

Failed JSON logging from `ReportEngine/utils/config.py:66-68`:

JSON_ERROR_LOG_DIR: str = Field(
    "logs/json_repair_failures", description="无法修复的JSON块落盘目录"
)

Multi-attempt parsing from `ReportEngine/utils/config.py:56-58`:

CHAPTER_JSON_MAX_ATTEMPTS: int = Field(
    2, description="章节JSON解析失败时的最大尝试次数"
)

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment