MCPcopy Index your code
hub / github.com/KnowledgeXLab/LeanRAG / extract_first_complete_json

Function extract_first_complete_json

_cluster_utils.py:47–71  ·  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

45 if item['parent'] not in e_l[index+1]:
46 print(item['entity_name'],item['parent'])
47def extract_first_complete_json(s: str):
48 """Extract the first complete JSON object from the string using a stack to track braces."""
49 stack = []
50 first_json_start = None
51
52 for i, char in enumerate(s):
53 if char == '{':
54 stack.append(i)
55 if first_json_start is None:
56 first_json_start = i
57 elif char == '}':
58 if stack:
59 start = stack.pop()
60 if not stack:
61 first_json_str = s[first_json_start:i+1]
62 try:
63 # Attempt to parse the JSON string
64 return json.loads(first_json_str.replace("\n", ""))
65 except json.JSONDecodeError as e:
66 logger.error(f"JSON decoding failed: {e}. Attempted string: {first_json_str[:50]}...")
67 return None
68 finally:
69 first_json_start = None
70 logger.warning("No complete JSON object found in the input string.")
71 return None
72def extract_json_from_cluster(s:str):
73 import re
74 s=s.replace('*', '')

Callers 1

convert_response_to_jsonFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected