Models asked for JSON often wrap it in prose or code fences, or add trailing commas. Extract the first JSON object from the text:
json … or …), use the content of the first one.{ to the matching closing } (track nesting and ignore
braces inside strings).} or ] (outside strings) and parse.Return the parsed dictionary, or None if no valid object can be extracted.
Implement extract_json. Input: text: str. Returns: dict | None.
import json
def extract_json(text: str):
try:
return json.loads(text)
except ValueError:
return None
Run executes the public tests. Submit grades against public and hidden tests.
Models asked for JSON often wrap it in prose or code fences, or add trailing commas. Extract the first JSON object from the text:
json … or …), use the content of the first one.{ to the matching closing } (track nesting and ignore
braces inside strings).} or ] (outside strings) and parse.Return the parsed dictionary, or None if no valid object can be extracted.
Implement extract_json. Input: text: str. Returns: dict | None.
import json
def extract_json(text: str):
try:
return json.loads(text)
except ValueError:
return None
Run executes the public tests. Submit grades against public and hidden tests.