Getting Reliable JSON and Structured Output
By the Katkat team · Updated · 9 min read
Quick overview
Learn how to get reliable JSON from LLMs: schemas, constrained decoding, tool-call formats, and validate-and-repair loops, with worked numbers for interviews.
After this lesson you will be able to explain why a language model can emit broken JSON even when told not to, and what each technique does to prevent it. You will be able to compare prompt-only JSON, JSON mode, tool calling and schema-constrained decoding, and to design a validate-and-repair loop with a numeric estimate of its reliability and cost. You will also be able to say what none of these techniques guarantee, which is where most interview follow-ups go.
Why structured output is hard
A model generates one token at a time by sampling from a probability distribution (see Decoding: Greedy, Temperature, Top-k and Top-p). Nothing in that process knows about braces, quotes or commas. The model has learned from training data that JSON usually looks a certain way, and that is all.
Typical failures when you only ask politely in the prompt:
- Prose around the JSON ("Sure! Here is the result:") or Markdown code fences.
- Trailing commas, single quotes, unescaped quotes or newlines inside strings.
- Missing required keys, extra keys, or wrong types (
"42"instead of42). - Truncation: the output hits the maximum token limit in the middle of an object.
- Values outside the allowed set, such as
"priority": "urgent-ish"when onlylow,mediumandhighare valid.
Downstream code is strict, so one malformed response can become an exception, a failed job or, worse, silently wrong data. The goal is to move as much checking as possible from "hope" to "guarantee", and to catch the rest cheaply.
Schemas: the contract
A schema is the machine-readable description of what you want. JSON Schema is the common format. In Python you usually define a Pydantic model (or a dataclass or TypedDict) and generate JSON Schema from it. In TypeScript the equivalent is a Zod schema or an interface-derived schema.
A good schema does real work for you:
- Types and required fields say what must be present.
- Enums turn a fuzzy label into a closed set. Prefer
"enum": ["billing", "bug", "other"]over free text. - Descriptions on fields are part of the prompt. The model reads them, so "ISO 8601 date, e.g. 2025-03-14" helps.
- No extra keys (
additionalProperties: false) keeps output predictable. - Nullable or "unknown" options let the model say it does not know instead of inventing a value to satisfy a required field.
Keep schemas flat and small where you can. Deep nesting, large unions and long enums cost tokens in the prompt and make errors more likely. Providers that enforce schemas typically support only a subset of JSON Schema, so check the documentation of the one you use before relying on a feature such as regex patterns or numeric ranges.
Four ways to get structure
| Approach | Mechanism | Guarantees valid JSON? | Guarantees schema match? | Main weakness |
|---|---|---|---|---|
| Prompt only | Instructions plus an example | No | No | Fails at some rate; needs parsing and retries |
| JSON mode | Provider-side constraint to syntactically valid JSON | Usually yes (check provider docs) | No | Right syntax, wrong keys or types |
| Tool / function calling | Model emits a tool name and arguments following a declared schema | Depends on provider and settings | Often, not always | Arguments still need validation; format varies by vendor |
| Schema-constrained decoding | Token mask built from the schema at each step | Yes | Yes, for the supported schema subset | Limited schema features; says nothing about whether values are correct |
Exact names, flags and guarantees vary by vendor and change over time, so treat the "Guarantees" columns as the general pattern and verify against current documentation. For self-hosted models, open-source libraries and inference servers implement constrained decoding using grammars or schemas.
Constrained decoding: how the mask works
The idea is to restrict sampling to tokens that keep the output a valid prefix of something the schema allows.
- Compile the schema (or a grammar or regex) into a state machine. Each state knows which next characters are legal.
- Before each sampling step, work out which vocabulary tokens are legal in the current state. Tokens can span several characters, so this is computed on token strings (see Tokenization). Implementations precompute or cache these masks per state so the per-step overhead stays small.
- Set the logits of illegal tokens to negative infinity, then apply softmax and sample as normal.
- Advance the state machine with the chosen token. Repeat until the machine reaches an accepting state.
Worked example. The output so far is {"age": and the schema says age is an integer. Pretend only three candidate tokens matter, with these logits: "1" = 2.0, "2" = 1.0 and "yes" = 3.0.
- Unconstrained: exp values are 7.389, 2.718 and 20.086, summing to 30.193. The model picks
yeswith probability 20.086 / 30.193 = 66.5%, which breaks the schema. - Constrained:
yesis masked. The remaining sum is 7.389 + 2.718 = 10.107. Now"1"has probability 73.1% and"2"has 26.9%.
The mask does not make the model smarter. It renormalises probability over legal options, so a wrong-but-legal value such as the wrong age can still be chosen.
Trade-offs to know:
- Syntax is guaranteed, semantics are not. A perfectly valid object can contain a fabricated invoice number.
- Forced fields invite invention. If a required field has no support in the input, the model must still fill it. Offer null or an
"unknown"enum value. - Truncation still breaks it. If generation stops at the token limit before the object is complete, the output is invalid. Check the finish reason.
- Order matters. Generation is left to right, so put a short
reasoningorevidencefield before the final answer field if you want the model to think first. Averdictkey first commits the model before it has reasoned. - Constraints can distort quality. Forcing an unnatural path can lower answer quality for hard tasks. Measure it with an eval rather than assuming it is free.
Tool-call formats
Tool calling is structured output with a standard envelope. You declare tools, each with a name, a description and a parameter schema. The model replies with a tool name and arguments instead of prose. Your code executes the call and sends the result back (see Tool Calling and the Agent Loop).
Details that matter for reliability:
- Arguments often arrive as a JSON string, not an object. You must parse it, and parsing can fail.
- Parallel calls: a single response may contain several tool calls, each with its own ID that you must echo back with the result.
- Tool choice controls let you force a particular tool, allow any, or forbid tools. Forcing one tool with a schema is a common way to extract structured data even when you never plan to "run" the tool.
- Format differs by vendor. Field names and nesting differ, so wrap them behind one internal interface.
- Arguments are untrusted input. Validate them as you would a web request body, especially if they reach a database or shell (see Prompt Injection and Guardrails).
Good descriptions and parameter names matter as much as the schema. See Designing Tools an Agent Can Use.
Validation and repair loops
Even with constraints, you validate. A practical pipeline has three layers:
- Parse: is it JSON at all? Strip code fences if you must, but do not write elaborate regex rescues.
- Schema validate: types, required keys, enums (Pydantic, Zod or a JSON Schema validator).
- Semantic validate: business rules the schema cannot express. Does the date lie in the past? Does the product ID exist? Does the quoted text actually appear in the source document?
On failure, retry with feedback: send the original request, the bad output and the specific error message ("priority must be one of low, medium, high; got 'urgent'"). Retrying the identical request at temperature 0 will usually return the identical failure, so change something: add the error, raise temperature slightly, or switch to a stronger model. Cap retries (two is common), then fall back to a default, a human queue or a clear error.
Worked example. Prompt-only JSON is valid and schema-correct 94% of the time, so the failure rate is p = 0.06. With up to 2 retries, assume attempts fail independently.
- Probability all three attempts fail: 0.06³ = 0.000216, so success is 99.98%.
- At 10,000 requests a day, failures drop from 600 to about 2.
- Expected calls per request: 1 + 0.06 + 0.06² = 1 + 0.06 + 0.0036 = 1.0636, so about 6.4% extra cost.
The independence assumption is optimistic. Failures cluster on hard or odd inputs, so the true residual rate is higher. Measure it on real traffic instead of trusting the formula. Retries also add latency on the unlucky requests, which matters for tail latency (see Streaming and Latency Metrics).
Production concerns
- Streaming: partial JSON is not parseable until it closes. Either wait for the full object, use an incremental parser, or stream a plain-text field separately from structured metadata.
- Evaluate it: track the parse rate, schema-valid rate, retry rate and field-level accuracy separately. Syntactic success can hide a drop in correctness (see LLM Evaluation and LLM-as-a-Judge).
- Version schemas together with prompts. Adding a required field is a breaking change for old cached outputs and for downstream consumers.
- Prompting still matters: a short example output, clear field descriptions and a stated fallback ("use null if absent") reduce semantic errors that no constraint can catch (see Prompt Engineering That Survives Production).
- Log failures with the raw output so you can find patterns.
How does this come up in interviews?
1. "The model sometimes returns invalid JSON. How do you fix it?" Start by measuring which failure it is: unparseable, wrong schema, truncated or semantically wrong. Then layer defences: a schema with enums, structured-output or tool-calling mode, or constrained decoding if self-hosting, then validation with a capped retry loop that feeds the error back. Finish by monitoring the parse and retry rates in production.
2. "How does constrained decoding guarantee valid output?" The schema is compiled into a state machine, and at each step tokens that would leave the set of valid outputs get their logits set to negative infinity before sampling. Probability is renormalised over legal tokens, so the syntax is always valid. It does not guarantee correct values, and it cannot help if generation is truncated by a token limit.
3. "JSON mode vs tool calling vs prompt-only: when do you use each?" Prompt-only is fine for prototypes or when you have strong validation and retries. JSON mode ensures syntax but not your schema. Tool calling or schema-enforced output is the default for production extraction, and tool calling is also required when the model must trigger actions. I would validate in all cases.
4. "Your extraction pipeline is 99% schema-valid but users report wrong data. Why?" Schema validity measures form, not truth. Likely causes are forced required fields that the model fills with guesses, ambiguous field descriptions, or missing semantic checks. I would add null options, check values against the source text or reference data, and evaluate field-level accuracy on a labelled set.
5. "Design a retry loop for structured output." Parse, schema-validate and rule-validate, then on failure re-prompt with the bad output and the exact error. Cap at about two retries, change something between attempts, and fall back to a default or human review. Estimate the cost as 1 + p + p² calls per request on average, where p is the per-attempt failure rate.
Common mistakes
- Trusting JSON mode or constrained decoding and skipping validation entirely.
- Treating schema-valid as correct, and not checking values against the source or reference data.
- Making fields required when the input may not contain them, which pushes the model to invent values.
- Retrying the same request at temperature 0 and expecting a different result.
- Not checking the finish reason, so truncated output goes to the parser as if it were complete.
- Placing the final answer field before the reasoning field.
- Writing huge, deeply nested schemas with features the provider does not support.
- Forgetting that tool-call arguments are untrusted input.
- Reporting only the "valid JSON rate" and never measuring field-level accuracy.