|
import re |
|
import json |
|
from typing import Any, List |
|
|
|
def parse_json_codefences(text: str) -> List[Any]: |
|
""" |
|
Extracts all ```json ... ``` code blocks from `text`, parses each as JSON, |
|
and returns a list of resulting Python objects. |
|
""" |
|
|
|
pattern = re.compile(r"```json\s+(.*?)\s+```", re.DOTALL | re.IGNORECASE) |
|
results = [] |
|
for match in pattern.finditer(text): |
|
json_str = match.group(1).strip() |
|
try: |
|
data = json.loads(json_str) |
|
if isinstance(data, list): |
|
results.extend(data) |
|
else: |
|
results.append(data) |
|
except json.JSONDecodeError as e: |
|
print(f"⚠️ Failed to parse JSON block:\n{json_str}\nError: {e}") |
|
return results |
|
|
|
def parse_python_codefences(text: str) -> List[str]: |
|
""" |
|
Extracts all ```python ... ``` code blocks from `text` |
|
""" |
|
|
|
pattern = re.compile(r"```python\s+(.*?)\s+```", re.DOTALL | re.IGNORECASE) |
|
results = "" |
|
|
|
for match in pattern.finditer(text): |
|
python_str = match.group(1).strip() |
|
results = python_str |
|
|
|
return results |
|
|