MCPcopy Create free account
hub / github.com/KnowledgeXLab/LeanRAG / extract_values_from_json

Function extract_values_from_json

tools/_utils.py:78–99  ·  view source on GitHub ↗

Extract key values from a non-standard or malformed JSON string, handling nested objects.

(json_string, keys=["reasoning", "answer", "data"], allow_no_quotes=False)

Source from the content-addressed store, hash-verified

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

Callers 1

convert_response_to_jsonFunction · 0.70

Calls 1

parse_valueFunction · 0.70

Tested by

no test coverage detected