Skip to content

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

fix(research): parse first JSON value when adjacent values follow (#680)

Santh5449b2dc05cc
diff --git a/deeptutor/agents/research/utils/json_utils.py b/deeptutor/agents/research/utils/json_utils.py
index 4a5f71e03..1b052f160 100644
--- a/deeptutor/agents/research/utils/json_utils.py
+++ b/deeptutor/agents/research/utils/json_utils.py
@@ -36,20 +36,17 @@ def extract_json_from_text(text: str) -> Union[Dict[str, Any], List[Any], None]:
except json.JSONDecodeError:
pass
- # 3) Fragment parsing
- obj_match = re.search(r"\{[\s\S]*\}", text)
- if obj_match:
+ # 3) First JSON value in surrounding prose / adjacent values
+ decoder = json.JSONDecoder()
+ for i, ch in enumerate(text):
+ if ch not in "{[":
+ continue
try:
- return json.loads(obj_match.group(0))
+ parsed, _end = decoder.raw_decode(text[i:])
except json.JSONDecodeError:
- pass
-
- arr_match = re.search(r"\[[\s\S]*\]", text)
- if arr_match:
- try:
- return json.loads(arr_match.group(0))
- except json.JSONDecodeError:
- pass
+ continue
+ if isinstance(parsed, (dict, list)):
+ return parsed
return None
diff --git a/tests/agents/research/test_extract_json_adjacent.py b/tests/agents/research/test_extract_json_adjacent.py
new file mode 100644
index 000000000..7ac1deb35
--- /dev/null
+++ b/tests/agents/research/test_extract_json_adjacent.py
@@ -0,0 +1,15 @@
+"""extract_json_from_text must parse the first object when another follows."""
+
+from deeptutor.agents.research.utils.json_utils import extract_json_from_text
+
+
+def test_adjacent_objects_returns_first() -> None:
+ assert extract_json_from_text('{"a": 1}{"b": 2}') == {"a": 1}
+
+
+def test_object_then_array_returns_object() -> None:
+ assert extract_json_from_text('{"a": 1}[2, 3]') == {"a": 1}
+
+
+def test_trailing_prose_still_works() -> None:
+ assert extract_json_from_text('result: {"x": true} done') == {"x": True}