2026-04-02 12:00:00 +08:00
|
|
|
"""Shared JSON helpers (fenced markdown, brace extraction)."""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
2026-03-11 13:46:07 +08:00
|
|
|
import re
|
|
|
|
|
|
|
|
|
|
_MARKDOWN_JSON_FENCE_RE = re.compile(
|
|
|
|
|
r"^\s*```(?:json)?\s*(.*?)\s*```\s*$",
|
|
|
|
|
re.IGNORECASE | re.DOTALL,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def extract_json_payload(raw_response: str | None) -> str:
|
2026-04-02 12:00:00 +08:00
|
|
|
"""Strip optional ```json fences and return the outermost `{...}` object substring."""
|
2026-03-11 13:46:07 +08:00
|
|
|
cleaned = (raw_response or "").strip()
|
|
|
|
|
fenced_match = _MARKDOWN_JSON_FENCE_RE.match(cleaned)
|
|
|
|
|
if fenced_match:
|
|
|
|
|
cleaned = fenced_match.group(1).strip()
|
|
|
|
|
|
|
|
|
|
if cleaned.startswith("{") and cleaned.endswith("}"):
|
|
|
|
|
return cleaned
|
|
|
|
|
|
|
|
|
|
start = cleaned.find("{")
|
2026-04-08 15:37:09 +08:00
|
|
|
if start == -1:
|
|
|
|
|
return cleaned
|
|
|
|
|
depth = 0
|
|
|
|
|
for i, ch in enumerate(cleaned[start:], start):
|
|
|
|
|
if ch == "{":
|
|
|
|
|
depth += 1
|
|
|
|
|
elif ch == "}":
|
|
|
|
|
depth -= 1
|
|
|
|
|
if depth == 0:
|
|
|
|
|
return cleaned[start : i + 1].strip()
|
2026-03-11 13:46:07 +08:00
|
|
|
|
|
|
|
|
return cleaned
|