Structured Output From LLMs: JSON Schemas, Validation and the Retry Loop You Need Anyway
Asking a model for JSON is easy. Getting valid, schema-conforming JSON ten thousand times in a row is an engineering problem. How I validate, repair and retry without burning tokens.

The first time you ask a model to "respond in JSON," it works. The demo goes well. Then the pipeline runs overnight against 12,000 support tickets, and in the morning you find 140 failures: a trailing comment, a field named priority_level instead of priority, a markdown fence wrapped around the whole thing, and one response that simply apologised.
A 1.2% failure rate sounds small until it is the reason a batch job pages someone at 3am. Structured output is not a prompt trick. It is a contract, and contracts need enforcement.
Use the native mode first
Every serious provider now offers some form of constrained output — JSON mode, tool calling, or full schema enforcement. Use it. Constrained decoding removes the entire class of "not valid JSON" errors because the model literally cannot emit a token that breaks the grammar.
What it does not remove:
- Semantic errors. The JSON is valid, the
categoryfield is a string, and the string is "billing-ish". - Missing optional context. The model fills a required field with a plausible guess instead of admitting it does not know.
- Schema drift. You changed the schema in one place and the prompt in another.
So native mode is the floor, not the ceiling.
Define the schema once, in code
I keep the schema as the single source of truth and derive everything else from it — the provider's schema parameter, the prompt description, and the validator.
import { z } from class="text-code-string">"zod";
export const Ticket = z.object({
category: z.enum([class="text-code-string">"billing", class="text-code-string">"bug", class="text-code-string">"feature", class="text-code-string">"account", class="text-code-string">"other"]),
priority: z.enum([class="text-code-string">"low", class="text-code-string">"normal", class="text-code-string">"high", class="text-code-string">"urgent"]),
summary: z.string().min(10).max(280),
needs_human: z.boolean(),
});Enums are the most underused tool here. A free-text category field guarantees you will spend a week writing normalisation code. An enum forces the model to choose, and gives you an "other" bucket you can actually monitor.
Validate every response, even with constrained decoding
const parsed = Ticket.safeParse(JSON.parse(raw));
if (!parsed.success) {
log.warn(class="text-code-string">"schema_fail", { issues: parsed.error.issues, raw });
}Log the raw output on failure. Not the error message — the raw output. You will learn more from twenty failed responses than from any amount of prompt theory.
The repair-then-retry loop
When validation fails, there are two cheap moves before an expensive one:
1. Mechanical repair. Strip markdown fences, trim text before the first { and after the last }, remove trailing commas. This fixes a surprising share of failures from providers without strict modes. 2. Targeted retry. Send the model its own output plus the validator's error list and ask it to fix only those fields. This is far cheaper than regenerating from scratch, because the context is short. 3. Full retry with a different temperature, capped at one or two attempts.
After that, stop. Route the item to a dead-letter queue and move on. An infinite retry loop on a malformed input is how a $4 job becomes a $400 job.
| Step | Typical recovery | Cost | |---|---|---| | Mechanical repair | 40–60% of failures | Free | | Targeted retry | 70–85% of remainder | ~10% of original call | | Full retry | Most of what is left | 100% of original call | | Dead-letter | Everything else | Human time |
Make "I don't know" a valid answer
The single biggest quality improvement I have made to extraction pipelines is adding an explicit escape hatch. If a field is required and the model has no evidence, it will invent something. Give it null or an "unknown" enum value and tell it in the prompt that this is the correct answer when evidence is missing.
Your downstream code then handles unknown deliberately, instead of you discovering six weeks later that 8% of "urgent" tickets were guesses.
Keep the schema small
Long schemas degrade quality. Past fifteen or so fields, models start skipping, merging or confusing similar fields. If you need forty fields, split the job into two or three calls with focused schemas. It costs more tokens and produces measurably better data.
Version the contract
Put a schema_version in your stored records. When you add a field or tighten an enum, you will want to know which rows were produced under the old contract — especially when someone asks why last quarter's dashboard numbers moved.
What I actually monitor
- Schema failure rate per model and per prompt version
- Share of "other" and "unknown" values per field
- Retry rate and dead-letter volume per day
- Token cost per successful record, not per call
The last one matters most. A cheaper model with a 6% failure rate and expensive retries can cost more per good record than a pricier model that gets it right the first time.
Structured output is where LLM features stop being demos and start being software. Treat the schema like an API contract, enforce it at the boundary, and budget for the failures — because they are coming either way.
Paj Digital Labs
The engineering journal of Paj Digital Solutions — hosting, server infrastructure and web engineering, written by the people who run the servers.
Related reading

Streaming AI Responses: Partial Text Is Not a Completed Result
Streaming improves perceived speed but adds cancellation and partial-output states. Keep tool actions, structured results and saved answers behind a verified completion boundary.

Human Review Queues for AI: Confidence Is Not a Permission Slip
A model’s self-reported confidence does not establish accuracy. Route uncertain and consequential cases using tested rules, show reviewers the evidence and record their decisions without rubber-stamping.

AI Evaluation Sets: Keep the Test Data Out of the Tuning Loop
An evaluation stops being independent when every prompt revision is shaped around its answers. Separate development examples from held-out cases and measure meaningful failure categories.