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

Function extract_values_from_json

_cluster_utils.py:120–141  ·  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

118 # If conversion fails, return the value as-is (likely a string)
119 return value.strip('"') # Remove surrounding quotes if they exist
120def extract_values_from_json(json_string, keys=["reasoning", "answer", "data"], allow_no_quotes=False):
121 """Extract key values from a non-standard or malformed JSON string, handling nested objects."""
122 extracted_values = {}
123
124 # Enhanced pattern to match both quoted and unquoted values, as well as nested objects
125 regex_pattern = r'(?P<key>"?\w+"?)\s*:\s*(?P<value>{[^}]*}|".*?"|[^,}]+)'
126
127 for match in re.finditer(regex_pattern, json_string, re.DOTALL):
128 key = match.group('key').strip('"') # Strip quotes from key
129 value = match.group('value').strip()
130
131 # If the value is another nested JSON (starts with '{' and ends with '}'), recursively parse it
132 if value.startswith('{') and value.endswith('}'):
133 extracted_values[key] = extract_values_from_json(value)
134 else:
135 # Parse the value into the appropriate type (int, float, bool, etc.)
136 extracted_values[key] = parse_value(value)
137
138 if not extracted_values:
139 logger.warning("No values could be extracted from the string.")
140
141 return extracted_values
142
143
144def 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