json_repair Python Library vs Online Tools: When to Use Each (2026)
Have broken JSON right now? Fix it free in under 1 second — no signup.
Fix My JSON →json_repair Python Library vs Online JSON Repair Tools: When to Use Each (2026)
If you work with LLM-generated JSON, you've almost certainly encountered malformed output: missing quotes, truncated structures, trailing commas, unescaped characters. Two dominant solutions exist in 2026 — the json_repair Python library by @mangiucugna and online repair tools like AI JSONMedic. Both fix broken JSON, but they serve different workflows.
This guide compares them directly, shows you when to choose each, and gives you working code examples for both.
What Is json_repair (mangiucugna)?
json_repair is an open-source Python library maintained by Stefano Sanfilippo (@mangiucugna). It repairs malformed JSON strings with a specific focus on output from Large Language Models.
Current version: v0.63.3 (released August 19, 2026)
Install:
pip install json-repair
Python compatibility: 3.10, 3.11, 3.12, 3.13, 3.14
It fixes:
- Missing or mismatched quotation marks
- Trailing commas in objects and arrays
- Incomplete structures (truncated JSON from LLM token limits)
- Unescaped special characters
- Extra non-JSON content (e.g., markdown fences, preamble text)
- Python-style
True/False/Noneinstead of JSONtrue/false/null - Misplaced colons, commas, or brackets
Quick Comparison Table
| Feature | json_repair (Python) | AI JSONMedic (Online) |
|---|---|---|
| Setup required | pip install json-repair | None — browser |
| Automation/CI | ✅ Yes | ❌ No |
| Handles truncated JSON | ✅ Yes | ✅ Yes |
| Schema validation | ❌ Library-only (no built-in schema) | ✅ JSON Schema validator built-in |
| Visual diff/tree view | ❌ No | ✅ Yes |
| Privacy (client-side) | ✅ Local | ✅ Local |
| LLM pipeline integration | ✅ Native Python | ❌ Not scriptable |
| CLI tool | ✅ Yes | ❌ No |
| Cost | Free / open-source | Free |
| Latest version | v0.63.3 (Aug 19, 2026) | — |
Using json_repair in Python
Basic Usage
from json_repair import repair_json
# Broken LLM output
broken = '{"name": "Alice", "role": "engineer", "active": True,}'
fixed = repair_json(broken)
print(fixed)
# {"name": "Alice", "role": "engineer", "active": true}
Parse Directly to Dict (Skip json.loads)
import json_repair
# Returns a Python dict, not a string
data = json_repair.loads('{"key": "value", "count": 42,}')
print(data) # {'key': 'value', 'count': 42}
Handle Truncated JSON (LLM Token Limit Cutoff)
This is the most common LLM failure mode — JSON cut off mid-structure because the model hit its max_tokens limit.
from json_repair import repair_json
truncated = '{"items": [{"id": 1, "name": "First"}, {"id": 2, "name": "Sec'
fixed = repair_json(truncated)
print(fixed)
# {"items": [{"id": 1, "name": "First"}, {"id": 2, "name": "Sec"}]}
The library closes unclosed brackets and quotes, producing valid (if incomplete) JSON rather than crashing.
Strip Markdown Code Fences
LLMs often wrap JSON in markdown:
from json_repair import repair_json
llm_output = """Here is the data:json
{"user": "bob", "score": 95,}
"""
fixed = repair_json(llm_output)
# {"user": "bob", "score": 95}
Batch Processing in a Pipeline
from json_repair import repair_json
import json
def safe_parse(raw: str) -> dict | None:
"""Repair + parse LLM JSON, return None on total failure."""
try:
repaired = repair_json(raw, return_objects=True)
if isinstance(repaired, dict):
return repaired
except Exception:
pass
return None
llm_responses = [
'{"status": "ok", "count": 5,}',
"{'name': 'Alice', 'age': 30}",
'{"result": true, "data": [1, 2, 3',
]
for raw in llm_responses:
result = safe_parse(raw)
print(result)
CLI Usage
# Repair from stdin
echo '{"key": "value",}' | json_repair
# Repair a file
json_repair broken.json > fixed.json
# Repair and pretty-print
json_repair broken.json --indent 2
json_repair + Schema Validation: The Missing Piece
Here's the gap in json_repair alone: it doesn't validate schema. It fixes syntax, but it won't tell you whether the repaired JSON matches the structure your application expects.
For production LLM pipelines, you almost always need both:
- Repair — make it parseable
- Validate — confirm it matches your schema
from json_repair import repair_json
import jsonschema
import json
schema = {
"type": "object",
"required": ["name", "score", "active"],
"properties": {
"name": {"type": "string"},
"score": {"type": "number"},
"active": {"type": "boolean"}
},
"additionalProperties": False
}
def repair_and_validate(raw: str, schema: dict) -> tuple[dict | None, list[str]]:
"""Repair broken JSON, then validate against schema."""
errors = []
# Step 1: Repair
try:
repaired = json.loads(repair_json(raw))
except Exception as e:
return None, [f"Repair failed: {e}"]
# Step 2: Validate
validator = jsonschema.Draft7Validator(schema)
validation_errors = list(validator.iter_errors(repaired))
if validation_errors:
errors = [e.message for e in validation_errors]
return repaired, errors
return repaired, []
# Test
raw = '{"name": "Alice", "score": 92.5, "active": True,}'
data, errors = repair_and_validate(raw, schema)
if errors:
print(f"Schema errors: {errors}")
else:
print(f"Valid: {data}")
# Valid: {'name': 'Alice', 'score': 92.5, 'active': True}
For interactive development and ad-hoc debugging, the AI JSONMedic validator combines repair + JSON Schema validation in a single browser-based interface — no setup required.
When to Use Each
Use json_repair (Python Library) When:
- You're building a production LLM pipeline — batch processing, automated retries, CI/CD integration
- You need to repair at scale — thousands of responses per hour
- Python is your stack — native integration, no HTTP overhead
- You want CLI automation — pipe, script, cron jobs
- Offline/air-gapped environment — no browser, no API calls
Use AI JSONMedic (Online Tool) When:
- One-off debugging — you got a broken response and need to see what's wrong fast
- You need visual output — tree view, diff, structure highlighting
- Schema validation required alongside repair — test your JSON Schema against real output
- Non-technical team members — no Python knowledge required
- Exploring JSON structure — JSONPath, format conversion, minification
Use Both Together:
The ideal workflow for serious LLM development:
- Debug phase: Paste broken outputs into AI JSONMedic to understand failure patterns visually
- Build phase: Integrate
json_repairinto your Python pipeline for automated fixing - Validation phase: Add
jsonschemaafterjson_repair, reference your schema from AI JSONMedic's schema generator to build it fast - Monitor phase: Log repair events — high repair rates signal prompt engineering issues
json_repair vs Our Repair Engine: What's Different
Both json_repair and AI JSONMedic address the same core problem, but with different implementation approaches:
| Repair scenario | json_repair v0.63.3 | AI JSONMedic |
|---|---|---|
| Truncated JSON (token cutoff) | ✅ Closes open structures | ✅ Closes open structures |
| Python literals (True/None) | ✅ Converts to JSON | ✅ Converts to JSON |
| Markdown code fences | ✅ Strips automatically | ✅ Strips automatically |
| Single quotes | ✅ Converts to double | ✅ Converts to double |
| Trailing commas | ✅ Removes | ✅ Removes |
| Unescaped newlines in strings | ✅ Escapes | ✅ Escapes |
| Schema validation | ❌ Separate step | ✅ Built-in |
| Visual diff | ❌ Not available | ✅ Side-by-side diff |
| JSONPath query | ❌ Not available | ✅ Built-in |
The library and online tool complement rather than compete. json_repair belongs in your code; AI JSONMedic belongs in your browser.
Common json_repair Failure Modes (and Fixes)
Even a mature library like v0.63.3 has edge cases. Here are the patterns to watch for:
Total Garbage Input
from json_repair import repair_json
# No recoverable JSON structure
result = repair_json("Error: rate limit exceeded")
print(result) # "" (empty string — not parseable)
Fix: Check if result is empty before parsing. Implement retry with exponential backoff when repair returns empty.
Ambiguous Number/String Coercion
When a value like 42 appears where a string is expected, json_repair preserves the number type — which may break your schema.
# If schema expects {"id": "string"} but LLM sends {"id": 42}
# json_repair won't convert the type — schema validation catches this
Fix: Always follow json_repair with schema validation for typed fields.
Deeply Nested Truncation
Very deep JSON truncated mid-nesting can sometimes resolve ambiguously:
# LLM cuts off inside a deeply nested object
broken = '{"a": {"b": {"c": {"d": 1'
repaired = repair_json(broken)
# {"a": {"b": {"c": {"d": 1}}}} ← correct
In most cases this works, but test your specific LLM output patterns. Use AI JSONMedic's tree view to visually verify complex structures.
Production Integration Pattern
Here's a complete retry-with-repair pattern suitable for any LLM provider:
import json
import time
from json_repair import repair_json
import anthropic # or openai, google.generativeai, etc.
client = anthropic.Anthropic()
def call_llm_with_json_repair(prompt: str, max_retries: int = 3) -> dict:
"""
Call LLM, repair JSON response, retry on total failure.
Returns parsed dict or raises after max_retries.
"""
for attempt in range(max_retries):
try:
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{"role": "user", "content": prompt}]
)
raw = response.content[0].text
# Attempt normal parse first
try:
return json.loads(raw)
except json.JSONDecodeError:
pass
# Repair and retry
repaired = repair_json(raw, return_objects=True)
if isinstance(repaired, dict) and repaired:
return repaired
# Empty result — retry
if attempt < max_retries - 1:
time.sleep(2 ** attempt) # exponential backoff
continue
except Exception as e:
if attempt == max_retries - 1:
raise
time.sleep(2 ** attempt)
raise ValueError(f"Could not parse LLM JSON after {max_retries} attempts")
For more LLM JSON failure patterns and repair strategies, see the complete LLM JSON repair guide.
Frequently Asked Questions
Q: Is json_repair production-ready in 2026?Yes. v0.63.3 (August 2026) is stable and widely used in LLM production pipelines. It's actively maintained, supports Python 3.10–3.14, available on both PyPI and conda-forge, and has a public test suite. Use it with confidence, but always add schema validation downstream for typed data.
Q: How does json_repair handle LLM token limit cutoffs?It closes unclosed brackets and quotes using a best-guess algorithm. For simple structures this is reliable. For deeply nested or ambiguous truncations, verify the output against your schema. When debugging truncation patterns visually, paste into the AI JSONMedic tool.
Q: Does json_repair work with LangChain or LlamaIndex?Yes. Both LangChain and LlamaIndex have their own output parsers with repair logic, but you can replace or augment them with json_repair.loads(). See our structured output libraries comparison for how repair fits into the broader library ecosystem.
repair_json() returns a repaired JSON string. json_repair.loads() returns a Python object (dict, list, etc.) directly — equivalent to json.loads(repair_json(s)). Use loads() when you want the object directly without the intermediate string step.
Q: Can I use json_repair from the command line?
Yes. After pip install json-repair, run json_repair broken.json or pipe: echo '{"key": "val",}' | json_repair. For bulk file repair or CI pipelines this is the fastest path.
Schema mismatch. json_repair fixes syntax (parseable JSON) not semantics (correct types, required fields, valid values). Always validate against your schema after repair. Use AI JSONMedic's validator to build and test your schema before adding it to your pipeline.
Summary
json_repair v0.63.3 is the best Python library for automated LLM JSON repair in 2026. It handles every common failure mode, ships with a CLI, and integrates into any Python pipeline in minutes.
The gap it leaves — schema validation, visual inspection, one-off debugging — is exactly what online tools like AI JSONMedic cover.
Use them together: the library in your code, the online tool in your browser. Between the two, broken JSON stops being a production incident and starts being a one-line fix.
Related guides:- Best JSON Repair Tools 2026 — full comparison of 16+ tools
- LLM JSON Repair Guide — 7 failure patterns + fix strategies
- 8 Structured Output Libraries Ranked — Instructor, BAML, XGrammar & more
- DeepSeek R1 JSON Output Fix — model-specific repair guide
Schema for this page:
{
"@context": "https://schema.org",
"@graph": [
{
"@type": "Article",
"headline": "json_repair Python Library vs Online JSON Repair Tools: When to Use Each (2026)",
"description": "Compare json_repair Python library (v0.63.3 by mangiucugna) vs online JSON repair tools. Code examples, CLI usage, schema validation strategies, and when to use each.",
"author": {
"@type": "Person",
"name": "The JSON Medic",
"url": "https://aijsonmedic.com/authors/json-medic"
},
"datePublished": "2026-08-21",
"dateModified": "2026-08-21",
"publisher": {
"@type": "Organization",
"name": "AI JSONMedic",
"url": "https://aijsonmedic.com"
}
},
{
"@type": "FAQPage",
"mainEntity": [
{
"@type": "Question",
"name": "Is json_repair production-ready in 2026?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Yes. v0.63.3 (August 2026) is stable and widely used in LLM production pipelines. It supports Python 3.10–3.14, is available on PyPI and conda-forge, and has an active test suite. Always add schema validation downstream for typed data."
}
},
{
"@type": "Question",
"name": "How does json_repair handle LLM token limit cutoffs?",
"acceptedAnswer": {
"@type": "Answer",
"text": "It closes unclosed brackets and quotes using a best-guess algorithm. For simple structures this is reliable. For deeply nested or ambiguous truncations, verify output against your schema."
}
},
{
"@type": "Question",
"name": "Does json_repair work with LangChain or LlamaIndex?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Yes. You can replace or augment their output parsers with json_repair.loads(). It works with any Python LLM framework including LangChain, LlamaIndex, and direct Anthropic/OpenAI SDK calls."
}
},
{
"@type": "Question",
"name": "What is the difference between repair_json() and json_repair.loads()?",
"acceptedAnswer": {
"@type": "Answer",
"text": "repair_json() returns a repaired JSON string. json_repair.loads() returns a Python dict or list directly, equivalent to json.loads(repair_json(s)). Use loads() when you want the object without the intermediate string step."
}
},
{
"@type": "Question",
"name": "Can I use json_repair from the command line?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Yes. After pip install json-repair, run json_repair broken.json or pipe input: echo '{\"key\": \"val\",}' | json_repair. This is ideal for bulk file repair or CI pipelines."
}
},
{
"@type": "Question",
"name": "Why does my code still break after json_repair fixed the syntax?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Schema mismatch. json_repair fixes syntax (parseable JSON) not semantics (correct types, required fields). Always validate against your JSON Schema after repair."
}
}
]
}
]
}
Still dealing with broken JSON?
Paste it in and get it fixed in under 1 second — free, no signup, no install. Works with ChatGPT, Claude, n8n, and any AI output.
Fix My JSON Free →Related Articles