Extract key values from a non-standard or malformed JSON string, handling nested objects.
(json_string, keys=["reasoning", "answer", "data"], allow_no_quotes=False)
| 79 | return value.strip('"') # Remove surrounding quotes if they exist |
| 80 | |
| 81 | def extract_values_from_json(json_string, keys=["reasoning", "answer", "data"], allow_no_quotes=False): |
| 82 | """Extract key values from a non-standard or malformed JSON string, handling nested objects.""" |
| 83 | extracted_values = {} |
| 84 | |
| 85 | # Enhanced pattern to match both quoted and unquoted values, as well as nested objects |
| 86 | regex_pattern = r'(?P<key>"?\w+"?)\s*:\s*(?P<value>{[^}]*}|".*?"|[^,}]+)' |
| 87 | |
| 88 | for match in re.finditer(regex_pattern, json_string, re.DOTALL): |
| 89 | key = match.group('key').strip('"') # Strip quotes from key |
| 90 | value = match.group('value').strip() |
| 91 | |
| 92 | # If the value is another nested JSON (starts with '{' and ends with '}'), recursively parse it |
| 93 | if value.startswith('{') and value.endswith('}'): |
| 94 | extracted_values[key] = extract_values_from_json(value) |
| 95 | else: |
| 96 | # Parse the value into the appropriate type (int, float, bool, etc.) |
| 97 | extracted_values[key] = parse_value(value) |
| 98 | |
| 99 | if not extracted_values: |
| 100 | logger.warning("No values could be extracted from the string.") |
| 101 | |
| 102 | return extracted_values |
| 103 | |
| 104 | |
| 105 | def convert_response_to_json(response: str) -> dict: |
no test coverage detected