INNER CODE UNIT · Python
extract_json
wgpsec/AboutSecurity · scripts/grade_eval.py:112
def extract_json(text: str) -> dict | None:
"""Extract JSON object from text that may contain surrounding content."""
# Try direct parse
try:
return json.loads(text)
except (json.JSONDecodeError, TypeError):
pass
# Try to find JSON in the text
if not text:
return None
# Find first { and last }
start = text.find("{")
end = text.rfind("}")
if start >= 0 and end > start:
try:
return json.loads(text[start:end + 1])