Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions pyrit/exceptions/exceptions_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,10 +115,16 @@ def extract_json_from_string(response_msg: str) -> str:
str: The extracted JSON string if found, otherwise the original string.

"""
json_pattern = re.compile(r"\{.*\}|\[.*\]")
match = json_pattern.search(response_msg)
if match:
return match.group(0)
decoder = json.JSONDecoder()
for index, char in enumerate(response_msg):
if char not in "[{":
continue

try:
_, end_index = decoder.raw_decode(response_msg, idx=index)
return response_msg[index:end_index]
except json.JSONDecodeError:
continue

return response_msg

Expand Down
4 changes: 4 additions & 0 deletions tests/unit/exceptions/test_exceptions_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@ def test_remove_end_md_json(input_str, expected_output):
("No JSON here", "No JSON here"),
('jsn\n{"key": "value"}\n```', '{"key": "value"}'),
('Some text before JSON {"a": [1,2,3], "b": {"c": 4}} some text after JSON', '{"a": [1,2,3], "b": {"c": 4}}'),
(
'Some text before JSON {\n "key": "value",\n "nested": {"enabled": true}\n} some text after JSON',
'{\n "key": "value",\n "nested": {"enabled": true}\n}',
),
],
)
def test_extract_json_from_string(input_str, expected_output):
Expand Down
Loading