Reuse memoir JSON payload parsing

This commit is contained in:
Kevin
2026-03-11 13:46:07 +08:00
parent 32954d4b3f
commit 822aefe54b
4 changed files with 57 additions and 24 deletions

View File

@@ -0,0 +1,23 @@
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:
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("{")
end = cleaned.rfind("}")
if start != -1 and end != -1 and end > start:
return cleaned[start : end + 1].strip()
return cleaned