sagelearnai

Working with JSON and Errors

LLM apps are glue between unstructured text and structured systems. You'll constantly parse JSON from APIs, ask models to produce JSON, and validate it before trusting it. This lesson builds that muscle.

JSON basics in Python

python
import json
payload = {"name": "Asha", "tags": ["vip", "beta"], "score": 0.92, "active": True, "note": None}
s = json.dumps(payload, ensure_ascii=False, indent=2)   # dict → string
back = json.loads(s)                                    # string → dict
JSONPython
object {}dict
array []list
stringstr
numberint / float
true / falseTrue / False
nullNone

JSONL (one JSON object per line) is the standard format for datasets, eval sets and fine-tuning data, because it streams and appends easily.

Models produce almost JSON

Ask a model for JSON and you'll sometimes get:

text
Sure! Here's the JSON:
```json
{"intent": "refund", "order_id": "A-1234",}
```

That's prose around it, a markdown fence, and a trailing comma, so json.loads fails. Defenses, from weakest to strongest:

  1. Prompting: "Respond with only a JSON object, no prose."
  2. Lenient extraction: strip fences, take the outermost {…}.
  3. JSON mode / structured outputs: the provider constrains decoding so the output parses (Module 2).
  4. Validate with a schema, and retry with the error message if it fails.
python
import re, json

def extract_json(text: str):
    text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text.strip(), flags=re.M)
    start, end = text.find("{"), text.rfind("}")
    if start == -1 or end == -1:
        raise ValueError("no JSON object found")
    return json.loads(text[start:end + 1])

Validate with Pydantic

Parsing proves the syntax is right; validation proves the shape and values are right.

python
from typing import Literal
from pydantic import BaseModel, Field, ValidationError

class Ticket(BaseModel):
    intent: Literal["refund", "bug", "question", "other"]
    order_id: str | None = Field(default=None, pattern=r"^A-\d{4}$")
    urgency: int = Field(ge=1, le=5)

try:
    t = Ticket.model_validate(extract_json(model_output))
except (ValueError, ValidationError) as e:
    # Feed the precise error back to the model for one repair attempt
    model_output = llm(f"Your previous output was invalid: {e}\nReturn corrected JSON only.")

Pydantic can also emit a JSON Schema (Ticket.model_json_schema()), which you can pass straight to structured-output and tool-calling APIs.

LLM output extract parse validate use / orrepair-retry once

Errors: fail loudly, recover deliberately

CategoryExampleStrategy
Transient429, 503, timeoutRetry with exponential backoff + jitter
Permanent request error400 invalid param, 401Don't retry; fix code/config; alert
Bad model outputinvalid JSON, wrong enumRepair-retry once or twice, then fall back
Business-logic failureorder not foundReturn a clear message to the user/model
python
import logging
log = logging.getLogger(__name__)

def safe_extract(text: str) -> Ticket | None:
    for attempt in range(2):
        try:
            return Ticket.model_validate(extract_json(text))
        except (ValueError, ValidationError) as e:
            log.info("invalid output (attempt %d): %s", attempt + 1, e)
            text = llm_repair(text, str(e))
    return None          # caller decides the fallback: ask a human, default route…
Never eval() model output

Parsing model text with eval or exec lets anyone who can influence the model, including through prompt injection, run code on your server. Use json.loads and schemas.

Last reviewed 2026-11-05.