Improve parse_maybe_json.

This commit is contained in:
OK 2023-03-30 15:52:11 +02:00
parent 585ecc17c6
commit 9eda81d7eb
2 changed files with 9 additions and 5 deletions

View File

@ -30,21 +30,23 @@ def parse_response(content: str) -> Dict:
def parse_maybe_json(json_string):
if json_string is None:
return None
json_string = json_string.strip()
try:
# Attempt to parse the string as JSON
parsed_json = parse_response(json_string)
except Exception:
# If it fails, return the original string unchanged
if json_string.startswith('{') and json_string.endswith('}'):
return parse_maybe_json(json_string[1:-1])
return json_string
# If the parsed JSON is a list or dictionary, concatenate its values as a string
if isinstance(parsed_json, (list, dict)):
concatenated_values = []
for value in parsed_json.values() if isinstance(parsed_json, dict) else parsed_json:
concatenated_values.append(str(value))
return '\n'.join(concatenated_values)
# If the parsed JSON is a string, return it
return str(parsed_json)

View File

@ -69,12 +69,14 @@ class TestFunctionality(TestBotBase):
non_json_string = "This is not a JSON string."
self.assertEqual(parse_maybe_json(non_json_string), non_json_string)
json_array = '["value1", "value2", "value3"]'
expected_output = "value1\nvalue2\nvalue3"
self.assertEqual(parse_maybe_json(json_array), expected_output)
json_string = '"value1"'
expected_output = 'value1'
self.assertEqual(parse_maybe_json(json_string), expected_output)
json_struct = '{"This is a string."}'
expected_output = 'This is a string.'
self.assertEqual(parse_maybe_json(json_struct), expected_output)
async def test_on_message_event(self) -> None:
async def acreate(*a, **kw):