File size: 822 Bytes
359e0bf 0b81e37 359e0bf |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
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.
"""
# Regex to match ```json ... ``` fences (non-greedy, multiline)
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
|