Skip to content

Commit

Permalink
Ensure if string but meant dict that return {}
Browse files Browse the repository at this point in the history
  • Loading branch information
pseudotensor committed Aug 19, 2024
1 parent 445a15b commit 14cc281
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
6 changes: 4 additions & 2 deletions src/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2447,12 +2447,14 @@ def repair_json_by_type(response, json_schema_type=None):
# WIP for later
if json_schema_type in ['object', None]:
from json_repair import repair_json
response_str = response
response = repair_json(response)
if response in ['""', """''""", '', None]:
return {}
try:
# assumes already dict
response_text = response
response = handle_json(json.loads(response))
if isinstance(response, list) and len(response) >= 1 and not response_text.startswith('['):
if isinstance(response, list) and len(response) >= 1 and not response_str.startswith('['):
response = response[-1] # take last if list, if was not pure list response
return json.dumps(response)
except Exception as e:
Expand Down
2 changes: 1 addition & 1 deletion src/version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "97397ec0166b2bcfc5753a8a48c3788f16a0e0f9"
__version__ = "445a15bca8cbddb70f1f3f52bccc2c23a8cc8b39"
13 changes: 13 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -873,6 +873,19 @@ def test_handle_json_no_schema():
assert handle_json(no_schema_json) == no_schema_json


def test_json_repair_on_string():
from json_repair import repair_json
response0 = 'According to the information provided, the best safety assessment enum label is "Safe".'

json_schema_type = 'object'
response = get_json(response0, json_schema_type=json_schema_type)
response = json.loads(response)
assert isinstance(response, dict) and not response

response = repair_json(response0)
assert isinstance(response, str) and response in ['""', """''""", '', None]


# Example usage converted to pytest test cases
def test_check_input_type():
# Valid URL
Expand Down

0 comments on commit 14cc281

Please sign in to comment.