MCPcopy Create free account
hub / github.com/Enfoirer/Text2GraphRAG / extract_values_from_json

Function extract_values_from_json

nano_graphrag/_utils.py:81–102  ·  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

79 return value.strip('"') # Remove surrounding quotes if they exist
80
81def 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
105def convert_response_to_json(response: str) -> dict:

Callers 1

convert_response_to_jsonFunction · 0.85

Calls 1

parse_valueFunction · 0.85

Tested by

no test coverage detected