AI Engineer Problems › Error Handling & Edge Cases

LLM JSON Code-Block Parser

Easy · Coding · Error Handling & Edge Cases · Asked at LinkedIn, Amazon, Stripe

LLM JSON Code-Block Parser

Language models frequently output JSON wrapped inside markdown code blocks (e.g., json ... ). Sometimes, they include additional leading/trailing newlines or whitespace.

Tasks

Implement a function parse_llm_json(raw_text) that:

  1. Trims any leading/trailing whitespace.
  2. Detects and extracts JSON string content if it is wrapped inside a markdown code block (handling both json and plain blocks).
  3. Parses the text into a Python object (dictionary or list).
  4. Raises a ValueError with a descriptive message if the string cannot be parsed into valid JSON.

Example

raw = "```json\n{\"sentiment\": \"positive\", \"score\": 0.95}\n```"
parse_llm_json(raw)
# Returns: {"sentiment": "positive", "score": 0.95}

Solve it in the browser on GenAIDojo