Extract and parse JSON from encoded string. Args: encode: String containing JSON (possibly wrapped in markdown code blocks) or already parsed JSON Returns: Parsed JSON object Raises: ValueError: If JSON format is invalid or cannot be parsed
(encode: str | Any)
| 54 | |
| 55 | |
| 56 | def json_format(encode: str | Any) -> Any: |
| 57 | """ |
| 58 | Extract and parse JSON from encoded string. |
| 59 | |
| 60 | Args: |
| 61 | encode: String containing JSON (possibly wrapped in markdown code blocks) or already parsed JSON |
| 62 | |
| 63 | Returns: |
| 64 | Parsed JSON object |
| 65 | |
| 66 | Raises: |
| 67 | ValueError: If JSON format is invalid or cannot be parsed |
| 68 | """ |
| 69 | if not isinstance(encode, str): |
| 70 | return encode |
| 71 | |
| 72 | if "'''json" in encode: |
| 73 | start = encode.find("'''json") + len("'''json") |
| 74 | end = encode.find("'''", start) |
| 75 | if start == -1 or end == -1: |
| 76 | raise ValueError("Invalid JSON format: missing closing '''") |
| 77 | encode = encode[start:end].strip().strip('"') |
| 78 | |
| 79 | if "```json" in encode: |
| 80 | start = encode.find("```json") + len("```json") |
| 81 | end = encode.find("```", start) |
| 82 | if start == -1 or end == -1: |
| 83 | raise ValueError("Invalid JSON format: missing closing ```") |
| 84 | encode = encode[start:end].strip().strip('"') |
| 85 | |
| 86 | encode = encode.replace("'", '"') |
| 87 | encode = encode.replace("\n", "") |
| 88 | |
| 89 | obj_start = encode.find("{") |
| 90 | obj_end = encode.rfind("}") |
| 91 | |
| 92 | arr_start = encode.find("[") |
| 93 | arr_end = encode.rfind("]") |
| 94 | |
| 95 | # Determine which format to use (prefer object if both exist) |
| 96 | if obj_start != -1 and obj_end != -1 and obj_end > obj_start: |
| 97 | count_open = encode.count("{") |
| 98 | count_close = encode.count("}") |
| 99 | if count_open != count_close: |
| 100 | logging.debug(f"Invalid JSON format: object bracket mismatch. Content: {encode[:200]}") |
| 101 | raise ValueError("Invalid JSON format: object bracket mismatch") |
| 102 | encode = encode[obj_start : obj_end + 1] |
| 103 | elif arr_start != -1 and arr_end != -1 and arr_end > arr_start: |
| 104 | count_open = encode.count("[") |
| 105 | count_close = encode.count("]") |
| 106 | if count_open != count_close: |
| 107 | logging.debug(f"Invalid JSON format: array bracket mismatch. Content: {encode[:200]}") |
| 108 | raise ValueError("Invalid JSON format: array bracket mismatch") |
| 109 | encode = encode[arr_start : arr_end + 1] |
| 110 | else: |
| 111 | # Try to parse as-is (might already be valid JSON) |
| 112 | pass |
| 113 |