InterviewPrepKit

Home / Coding / Agent Coding / Tools & Function Calling / Repairing Malformed JSON

Repairing Malformed JSON

hard 00:00
Solving tips
  • Always try a plain json.loads first; only repair when it actually fails, so you never corrupt valid input.
  • Keep each repair small, ordered, and documented — trailing commas, then quotes, then balancing brackets.
  • Return None on failure instead of raising, so the calling agent can retry or ask the model to regenerate.

Language models are the most common source of “almost JSON” — a tool call or structured response that is 99% valid but has a trailing comma, single quotes, or a missing closing brace. When you parse that output in an agent, a strict json.loads throws and the whole turn fails. A small, well-scoped repair pass rescues most of these cases without a heavyweight parser.

Task

Complete repair_json(text):

  1. First try json.loads(text) unchanged. If it parses, return the result immediately — never repair valid input.
  2. If it fails, apply a short, fixed sequence of common repairs and retry after each one (or all together, then retry):
    • Strip trailing commas that appear right before a } or ] (e.g. {"a": 1,} -> {"a": 1}).
    • Replace single quotes with double quotes (e.g. {'a': 1} -> {"a": 1}).
    • Balance brackets by appending the missing } or ] characters when the string ends with more opens than closes.
  3. If the string still cannot be parsed after the repairs, return None. Do not raise.

Keep the repairs simple and documented. This is a best-effort heuristic, not a full grammar.

Example

repair_json('{"a": 1, "b": 2}')        # -> {"a": 1, "b": 2}   (already valid)
repair_json('{"a": 1, "b": 2,}')       # -> {"a": 1, "b": 2}   (trailing comma)
repair_json("{'a': 1, 'b': 2}")        # -> {"a": 1, "b": 2}   (single quotes)
repair_json('{"a": 1, "b": [1, 2, 3')  # -> {"a": 1, "b": [1, 2, 3]}  (missing ] and })
repair_json('not json at all')         # -> None

Constraints

  • Return None on unrecoverable input rather than raising.
  • Do not use any third-party JSON-repair library; only the standard library (json) is allowed.
  • Never modify a string that already parses — check the happy path first.
  • The repairs are heuristics: they only need to handle the documented cases, not every malformed string.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug