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
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| JSON | Python |
|---|---|
object {} | dict |
array [] | list |
| string | str |
| number | int / float |
true / false | True / False |
null | None |
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:
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:
- Prompting: "Respond with only a JSON object, no prose."
- Lenient extraction: strip fences, take the outermost
{…}. - JSON mode / structured outputs: the provider constrains decoding so the output parses (Module 2).
- Validate with a schema, and retry with the error message if it fails.
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.
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.
Errors: fail loudly, recover deliberately
| Category | Example | Strategy |
|---|---|---|
| Transient | 429, 503, timeout | Retry with exponential backoff + jitter |
| Permanent request error | 400 invalid param, 401 | Don't retry; fix code/config; alert |
| Bad model output | invalid JSON, wrong enum | Repair-retry once or twice, then fall back |
| Business-logic failure | order not found | Return a clear message to the user/model |
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…eval() model outputParsing 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.