How to Repair Malformed JSON Braces Heuristically in Python
Heuristically fix malformed JSON by balancing braces and quotes, using a stack-based approach to add missing closing characters.
Python code
10 linesimport json
import re
def repair_json(text: str) -> str:
"""Heuristically repair malformed JSON by balancing braces and quotes."""
# Trim whitespace and handle leading/trailing garbage
text = text.strip()
# Remove common non-JSON decorations
text = re.sub(r'^(
Output
{"name": "Alice", "age": 30, "city": "New York"}
How it works
The function first strips whitespace and removes non-JSON decorations like trailing commas. Then it uses a stack to track opening braces, brackets, and quotes, ensuring every opening character gets a matching closing one. Incomplete strings or arrays are closed appropriately. The final text is parsed with json.loads to verify it's valid, returning the repaired string. This heuristic works well for common LLM response truncations.
Common mistakes
- Assuming the input is always a JSON object; arrays may need different handling.
- Not handling escaped quotes inside strings.
- Forgetting to strip trailing commas or other invalid punctuation.
- Relying on the heuristic for security-sensitive parsing without validation.
Variations
- Use a library like 'json_repair' that implements more robust error correction.
- For simple cases, append closing braces based on count instead of a full stack.
Real-world use cases
- Cleaning up truncated JSON responses from LLM APIs before parsing in your application.
- Repairing malformed config files or logs that get cut off during transmission.
- Fixing partial JSON payloads from webhooks before storing them in a database.
Sponsored
More from AI & LLM integration patterns
- Cache LLM Completions by Hashing the Prompt in Python easy
- Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo easy
- Circuit Breaker Pattern in Python for LLM API Calls medium
- Cosine Similarity to Retrieve Top K Chunks in Python easy
- Demonstrate Prompt Injection Bypass in Python easy
- How to Accumulate Streamed Tokens into a Final String in Python easy
Keep learning
Related tutorials and quizzes for this topic.