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
+6 -4
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)