24 lines
616 B
Python
24 lines
616 B
Python
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
|