Extract JSON from an LLM Reply

medium
Unit 12 · LLMs & Tokenization0/2 to milestone

You asked the model for JSON. It replied with "Sure! Here's the data:", then the JSON, then a friendly sign-off. Robust apps extract the JSON instead of crashing.

Implement extract_json(text) that returns the first complete JSON object ({...}) in text, parsed with json.loads, or None if there isn't one.

Rules

  • Scan for { and find its matching } by tracking nesting depth.
  • Braces inside JSON strings don't count, and strings can contain escaped quotes (\").
  • If a candidate isn't valid JSON, keep scanning from the next {.
  • The JSON may be wrapped in a Markdown code fence (```json ... ```). Your scan handles that naturally.
#llm#structured-output#parsing4 visible + 3 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Extract JSON from an LLM Reply · TechGradify