Repair Truncated Tool-Call JSON
Problem Statement
An LLM's tool-call arguments were cut off mid-JSON because of a token limit. Repair the string by closing any unterminated string and balancing open brackets, then parse it.
Background
A truncated JSON object like {"a": 1, "b": "hi needs: (1) close an open string quote if the number of unescaped " is odd, then (2) append the right closers for every unclosed { or [ in the correct (reverse) order. We assume truncation only drops trailing characters — the prefix is well-formed.
Your Task
Implement:
def repair_json(text):
Close an open string (if any), balance brackets, parse with json.loads, and return the resulting object.
Input Format
- text (str): possibly-truncated JSON.
Output Format
- The parsed object (dict or list).
Sample
print(repair_json('{"a": 1, "b": "hi'))
Output:
{'a': 1, 'b': 'hi'}
Example
print(repair_json('{"a": 1, "b": "hi')){'a': 1, 'b': 'hi'}- Scan for state: Iterate through the input
{"a": 1, "b": "hito track string status and bracket depth. The scanner identifies that the final character leaves the parser inside an unterminated string (due to the opening quote beforehi) and finds one unclosed opening brace{on the stack. - Close the string: Since the string state is active, append a closing double quote
"to the text, resulting in the intermediate string{"a": 1, "b": "hi". - Balance brackets: Process the stack in reverse order to close any remaining open structures. The single
{on the stack requires appending a closing brace}, yielding the fully repaired JSON string{"a": 1, "b": "hi"}. - Parse and return: The repaired string is valid JSON, so it is parsed into a Python dictionary with the key-value pairs
a: 1andb: hi. - The final output is
{'a': 1, 'b': 'hi'}
Constraints
- Truncation removes only a trailing suffix; the surviving prefix is valid.
- Count only unescaped quotes to decide if a string is open.
- Track a stack of
{/[seen outside strings; append matching closers in reverse.