Extract JSON content from a string response. Args: response (str): String containing JSON content, possibly within code blocks. Returns: dict: Extracted and parsed JSON content. Raises: ValueError: If no valid JSON content could be extracted.
(response: str)
| 4 | from typing import List |
| 5 | |
| 6 | def extract_json(response: str) -> dict: |
| 7 | """ |
| 8 | Extract JSON content from a string response. |
| 9 | |
| 10 | Args: |
| 11 | response (str): String containing JSON content, possibly within code blocks. |
| 12 | |
| 13 | Returns: |
| 14 | dict: Extracted and parsed JSON content. |
| 15 | |
| 16 | Raises: |
| 17 | ValueError: If no valid JSON content could be extracted. |
| 18 | """ |
| 19 | try: |
| 20 | evaluation_json = json.loads(response) |
| 21 | except json.JSONDecodeError: |
| 22 | # If JSON parsing fails, try to extract the content between ```json and ``` |
| 23 | match = re.search(r'```json\n(.*?)\n```', response, re.DOTALL) |
| 24 | if not match: |
| 25 | # If no match for ```json, try to extract content between ``` and ``` |
| 26 | match = re.search(r'```\n(.*?)\n```', response, re.DOTALL) |
| 27 | |
| 28 | if match: |
| 29 | evaluation_content = match.group(1) |
| 30 | evaluation_json = json.loads(evaluation_content) |
| 31 | else: |
| 32 | raise ValueError("Failed to extract valid JSON content") |
| 33 | return evaluation_json |
| 34 | |
| 35 | |
| 36 | def convert_score_fields(data: dict) -> dict: |
no outgoing calls
no test coverage detected