Improve parse_maybe_json.
This commit is contained in:
@@ -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)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user