Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(utils): decode trailing-prose JSON before repair

santhreal5c3e5bf560b5
diff --git a/deeptutor/utils/json_parser.py b/deeptutor/utils/json_parser.py
index 889b751d9..55638dff2 100644
--- a/deeptutor/utils/json_parser.py
+++ b/deeptutor/utils/json_parser.py
@@ -84,6 +84,19 @@ def parse_json_response(
except (json.JSONDecodeError, TypeError) as parse_error:
log.debug(f"Direct JSON parse failed: {parse_error}")
+ # Strategy 1b: first JSON value via raw_decode. Trailing prose with braces
+ # (common LLM slip) must not fall through to json-repair, which can invent
+ # a wrapping array and corrupt callers that expect a single object.
+ if isinstance(extracted_response, str):
+ stripped = extracted_response.lstrip()
+ for idx, ch in enumerate(stripped):
+ if ch in "{[":
+ try:
+ parsed, _end = json.JSONDecoder().raw_decode(stripped[idx:])
+ return parsed
+ except json.JSONDecodeError:
+ break
+
# Strategy 2: Try json-repair if available
if repair_json is None:
log.warning("json-repair library not installed, cannot repair malformed JSON")
diff --git a/tests/utils/test_json_parser.py b/tests/utils/test_json_parser.py
index bd7626328..49def6eb2 100644
--- a/tests/utils/test_json_parser.py
+++ b/tests/utils/test_json_parser.py
@@ -116,3 +116,15 @@ class TestSafeJsonLoads:
def test_explicit_none_fallback(self) -> None:
assert safe_json_loads("bad", fallback=None) is None
+
+
+class TestParseJsonResponseTrailingProse:
+ def test_trailing_brace_prose_keeps_object(self) -> None:
+ raw = '{"chapters":[{"title":"Intro"}]} note: see {schema}'
+ result = parse_json_response(raw)
+ assert result == {"chapters": [{"title": "Intro"}]}
+
+ def test_trailing_brace_prose_keeps_array(self) -> None:
+ raw = '[{"id":1},{"id":2}] trailing {x}'
+ result = parse_json_response(raw, fallback=None)
+ assert result == [{"id": 1}, {"id": 2}]