Repair Almost-Valid JSON

medium
Unit 23 · Structured Output0/2 to milestone

LLMs often produce almost valid JSON. Write a repair pass for the most common mistakes, applied outside of strings only:

  1. Strip a surrounding Markdown code fence (``` or ```json).
  2. Remove trailing commas before } or ].
  3. Replace Python literals True, False and None with true, false and null (whole words only).
  4. Convert single-quoted strings to double-quoted ones, escaping any " inside them.
  5. If the text ends with unclosed brackets or braces, append the missing closers in the right order (and close an unterminated string first).

Implement repair_json(text) returning the repaired string, and loads_lenient(text), which tries json.loads first and only repairs if that fails. If even the repaired text won't parse, loads_lenient raises ValueError.

#structured-output#parsing#llm2 visible + 3 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Repair Almost-Valid JSON · TechGradify