Even when asked for JSON, models produce things strict parsers reject: the answer wrapped in a markdown code fence, a friendly sentence before it, a trailing comma after the last item, Python-style literals (True, None) instead of true and null. Rather than discarding the response and paying for a retry, an agent can apply a short sequence of conservative repairs and parse again. The repairs must be careful not to change meaning: a comma inside a string value is data, not a trailing comma. This question implements the common fixes in a safe order and gives up cleanly when the text still does not parse.
Implement repair_json.
repair_json(text) returns the parsed Python object, or raises ValueError if no repair makes it valid JSON. Apply these steps in order, parsing with json.loads after each attempt and returning at the first success (try the raw text first).{ or [ to the last matching closing } or ] (the outermost span, ignoring leading and trailing prose). 3. Remove trailing commas: a comma followed only by whitespace and then } or ], outside string literals. 4. Replace the bare words True, False and None (outside string literals, whole words) with true, false and null.Implement string-aware scanning with a small state machine that tracks whether you are inside a double-quoted string (and handles backslash escapes), so steps 3 and 4 never touch string contents.
json.loads raises json.JSONDecodeError, a subclass of ValueError.
No results yet
Run your code to check it against the examples, or submit to run every test.