MCPcopy Create free account
hub / github.com/TIGER-AI-Lab/TheoremExplainAgent / extract_json

Function extract_json

src/utils/utils.py:48–79  ·  view source on GitHub ↗

Extract and parse JSON content from a text response. Attempts to parse the response as JSON directly, then tries to extract JSON from code blocks if direct parsing fails. Args: response (str): The text response containing JSON content Returns: dict: The parsed JSON

(response: str)

Source from the content-addressed store, hash-verified

46 return code
47
48def extract_json(response: str) -> dict:
49 """Extract and parse JSON content from a text response.
50
51 Attempts to parse the response as JSON directly, then tries to extract JSON from code blocks
52 if direct parsing fails.
53
54 Args:
55 response (str): The text response containing JSON content
56
57 Returns:
58 dict: The parsed JSON content as a dictionary, or empty list if parsing fails
59
60 Note:
61 Will attempt to parse content between ```json markers first, then between generic ``` markers
62 """
63 try:
64 evaluation_json = json.loads(response)
65 except json.JSONDecodeError:
66 # If JSON parsing fails, try to extract the content between ```json and ```
67 match = re.search(r'```json\n(.*?)\n```', response, re.DOTALL)
68 if not match:
69 # If no match for ```json, try to extract content between ``` and ```
70 match = re.search(r'```\n(.*?)\n```', response, re.DOTALL)
71
72 if match:
73 evaluation_content = match.group(1)
74 evaluation_json = json.loads(evaluation_content)
75 else:
76 # return empty list
77 evaluation_json = []
78 print(f"Warning: Failed to extract valid JSON content from {response}")
79 return evaluation_json
80
81def _fix_unicode_to_latex(text: str, parse_unicode: bool = True) -> str:
82 """Convert Unicode symbols to LaTeX source code.

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected