JSON Tool-Arg Repair
Background
LLM-emitted JSON is often almost valid: it may be wrapped in a ```json fence, use single quotes, have a trailing comma after the last value, or carry surrounding commentary. A robust agent's tool-call dispatch tries json.loads first, then applies cheap progressive repairs before giving up.
Problem statement
Implement repair_json(text) returning a Python object (dict, list, etc.) parsed from the input. Attempt repairs in this order: (1) raw json.loads, (2) strip Markdown code fence, (3) replace single quotes with double, (4) remove trailing commas before } or ]. If none succeed, raise ValueError.
Input
text—str(orNone). The raw model output.
Output
Returns the parsed object (whatever json.loads would produce on success).
Examples
Example 1 — clean JSON
Input: '{"a": 1}'
Output: {"a": 1}
Example 2 — markdown code fence
Input: '```json\n{"a": 1}\n```'
Output: {"a": 1}
Example 3 — single quotes
Input: "{'a': 1}"
Output: {"a": 1}
Example 4 — trailing comma
Input: '{"a": 1,}'
Output: {"a": 1}
Constraints
- Raises
ValueErrorif all repairs fail. Noneor empty input raisesValueError.- Repairs are applied in a defined order; the first one that parses wins.
Notes
- Why progressive. Don't run all repairs at once — they can interact (e.g. replacing single quotes inside a string field changes the meaning). Try in order and stop on first success.
- Production extras. Real implementations add: strip leading commentary up to the first
{/[, balance braces if truncated, repair unquoted keys, etc.
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Example: already-clean JSON object
- •Reference: markdown json fence stripped
- •Sample: single quotes converted to double