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

Function extract_first_complete_json

tools/_utils.py:31–55  ·  view source on GitHub ↗

Extract the first complete JSON object from the string using a stack to track braces.

(s: str)

Source from the content-addressed store, hash-verified

29
30
31def extract_first_complete_json(s: str):
32 """Extract the first complete JSON object from the string using a stack to track braces."""
33 stack = []
34 first_json_start = None
35
36 for i, char in enumerate(s):
37 if char == '{':
38 stack.append(i)
39 if first_json_start is None:
40 first_json_start = i
41 elif char == '}':
42 if stack:
43 start = stack.pop()
44 if not stack:
45 first_json_str = s[first_json_start:i+1]
46 try:
47 # Attempt to parse the JSON string
48 return json.loads(first_json_str.replace("\n", ""))
49 except json.JSONDecodeError as e:
50 logger.error(f"JSON decoding failed: {e}. Attempted string: {first_json_str[:50]}...")
51 return None
52 finally:
53 first_json_start = None
54 logger.warning("No complete JSON object found in the input string.")
55 return None
56
57def parse_value(value: str):
58 """Convert a string value to its appropriate type (int, float, bool, None, or keep as string). Work as a more broad 'eval()'"""

Callers 1

convert_response_to_jsonFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected