File size: 1,269 Bytes
359e0bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b81e37
 
 
 
359e0bf
 
 
506a87c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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

def parse_python_codefences(text: str) -> List[str]:
    """
    Extracts all ```python ... ``` code blocks from `text`
    """
    # Regex to match ```python ... ``` fences (non-greedy, multiline)
    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