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.

Medium Python 3.9+ Aug 9, 2026 AI & LLM integration patterns 13 views 0 copies

Python code

10 lines
Python 3.9+
import 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

stdout
{"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

  1. Use a library like 'json_repair' that implements more robust error correction.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from AI & LLM integration patterns

Related tutorials and quizzes for this topic.