# Reliable JSON from LLMs: constrain the decoder, verify the values

Grammar-level enforcement kills malformed JSON; schema design and semantic checks are what stop wrong-but-well-shaped data.

> How do you make structured JSON output from an LLM reliable?

## Short answer

Make the invalid output impossible, then check what remains: compile your schema into a grammar that masks disallowed tokens at every decoding step, validate the result into typed objects, retry with the specific validation error, and measure field-level accuracy because a structurally perfect object can still hold the wrong value.

Constrained decoding removes one whole class of failure — syntax — and that class is the easiest to over-value. Once structure is enforced, the residual errors are **semantic**: a plausible enum-adjacent category, a wrong severity, an empty list where the model should have asked a question instead. Those need schema design, validation, labeled evaluation, and routing, not a stronger prompt.

- **Schema-valid, pilot**: 1.000 in all structured conditions
- **Free-form baseline**: 0.000 JSON and schema validity
- **Dominant residual failure**: False confidence, then category mismatch

## JSON is a pattern the model imitates, not a rule it obeys

An LLM picks each token from a probability distribution over its vocabulary. Nothing in that distribution encodes a grammar; JSON is a pattern the model has seen often enough to imitate, and imitation is probabilistic. The arithmetic compounds fast: a model that gets a field right 99% of the time produces a fully correct twenty-field record only about 82% of the time. That compounding, not insufficient sternness in the prompt, is why instruction-hardening plateaus.

The failures are several distinct problems, each with a different fix:

- **Truncation** — the token budget expires mid-object. Fix by sizing the budget from the schema and by masking end-of-sequence until the document closes.
- **Wrapping** — a preamble or fenced code block around the object. Fix with a tolerant extractor or decoder-level enforcement.
- **Type drift** — the string "3" where an integer belongs. Fix in the validator, with coercion rules you chose on purpose.
- **Enum drift** — a plausible synonym where the schema wanted a closed value. Fix by enforcing enum membership at decode time.
- **Escaping errors** — an unescaped quote inside a string value. Fix with grammar masking.

Prompt instructions nudge the distribution; masking removes options from it entirely. That difference is why one approach converges and the other asymptotes.

> A model that is right 99% of the time per field is wrong on a fifth of its twenty-field records.

## Constrained decoding: tokens that cannot be sampled

Constrained decoding compiles the schema into an automaton and edits the model's choices in flight. The JSON Schema becomes a context-free grammar or finite-state machine; at every decode step each vocabulary token is tested — does appending its bytes keep the output a valid prefix? Tokens that fail get their logits set to negative infinity, so the sampler can never select them . The end-of-sequence token stays masked until the output is a complete document, which removes mid-structure truncation structurally rather than statistically .

Not all "structured output" is the same guarantee. A JSON mode that only promises the text will parse still lets required keys vanish and enums drift. A strict schema mode that constrains required properties and allowed values closes those holes. Read the provider's contract for what is actually enforced, not the feature's name.

The mechanism is not free. Building the mask means checking the whole vocabulary against the grammar at every step, and naive engines pay for it in latency . Earley-based pruning with state caching cuts that overhead substantially — one engine reports up to 2× speedup over prior implementations while preserving compliant output . Two practical boundaries: providers support only a subset of JSON Schema keywords, and the tokenizer matters, because masking operates on the byte strings that tokens represent .

> Note: Enforcement converts a probabilistic failure into an impossible one — but only for the property you actually encoded. Unsupported schema keywords silently fall back to best effort.

## Schema design and the validation-repair loop

A schema is an interface: it shapes both what the model can emit and what your code must handle. Four decisions move failure rates most. **Flatten before you nest**; every extra level is another place for an object to be abandoned mid-way. **Use enums instead of free strings** for closed sets, so drift becomes unrepresentable rather than merely discouraged. **Make optionality explicit** — a nullable field that is always present beats a key that sometimes disappears, because downstream code stops needing two code paths. **Keep reasoning fields short and put them before the answer field** if you want the model to commit to a category after stating evidence; this ordering effect is widely practiced but thinly evidenced, so treat it as a hypothesis to test on your own schema.

At runtime, parse into typed objects — Pydantic, Zod, a Go struct — and log the exact failing path. On failure, re-prompt with the concrete validation error and the offending fragment rather than "try again"; a generic retry resamples the same distribution and often reproduces the same defect. Bound the loop at two or three attempts, then fall through to a dead-letter path or a human. Whether error-fed repair converges faster than blind retry is not well established in the retrieved evidence; the bounded fallback is what makes the choice safe either way.

> The schema is not documentation of the output. It is the output's operating conditions.

## Schema validity saturates; correctness does not follow

Every layer so far guarantees shape. A 50-task ticket-triage pilot using gpt-4o-mini shows exactly where that stops: free-form output scored 0.000 on JSON and schema validity, while every structured condition — JSON-only prompting, schema validation, validation retry, validation repair, and the full reliability configuration — scored 1.000 on both . Once structure is enforced, parse errors stop discriminating between pipelines. What remained were semantic failures, with false confidence most frequent, followed by priority mismatch, customer-impact mismatch, and human-review mismatch .

Constrained decoding can make this worse in a subtle way. The grammar forces the model to emit some enum value; it cannot emit "unclear" unless you gave it that token. A forced choice looks like a decision, and a decision looks like confidence. The same mechanism can silently shorten a list, because ending the array is always grammatically legal.

So track four numbers, not one: schema-valid rate as a floor, field-level precision and recall against a labeled set, abstention calibration (does high stated confidence track correctness?), and human-review mismatch rate. The pilot is 50 synthetic tasks on one provider — a directional signal, not a law.

> Note: Monitoring only parse failures is how teams ship confidently wrong data: the dashboard goes green the moment the grammar works.

## One pipeline, five layers, from ticket text to typed record

Concrete application: turn free-text support tickets into a record with a closed-enum category, a closed-enum severity, a nullable affected-customer field, a shallow list of extracted entities, and a one-line summary.

Layer one is the schema: enums for both classifications, required for the fields your downstream code cannot do without, explicit null for the customer, nesting no deeper than two. Layer two is enforcement: a strict schema mode where the provider actually constrains required keys and enums, with the token budget sized from the schema's worst case. Layer three is a typed validator that returns structured errors, not a boolean. Layer four is a bounded repair loop that feeds the failing path and fragment back to the model, capped at two attempts before routing to human review. Layer five is an evaluation gate: a labeled sample scored for field-level accuracy and abstention calibration on every schema or model change.

The strongest caveat is that the hardest residual failures live above the token level. A grammar cannot encode whether "severity: high" is true. And when a model would benefit from deliberating before answering, forcing it to emit structure first can suppress that reasoning — plausible from how constrained decoding narrows the distribution, but not something the retrieved evidence settles. Where accuracy matters most, let the model reason in free text or a scratch field, then emit the typed record in a second constrained pass.

> Constrained decoding makes the output well-formed. Only evaluation makes it trustworthy.

## Common misconceptions

- **Myth:** If the output validates against the schema, the extraction was correct. **Reality:** Validation proves shape. In the ticket-triage pilot, every structured condition hit 1.000 schema validity while priority, customer-impact, and confidence errors persisted .
- **Myth:** Turning on JSON mode enforces my schema. **Reality:** Some JSON modes only guarantee the text parses. Required keys and enum membership are separate guarantees that only strict schema modes provide.
- **Myth:** Lowering temperature is the fix for malformed JSON. **Reality:** Temperature reduces sampling variance; it does not remove the possibility of an invalid token or a missing key. Grammar masking removes it.
- **Myth:** Retrying the same request until it parses is a reliability strategy. **Reality:** Blind retries resample the same distribution and can reproduce the same defect, while adding latency. Feed back the specific validation error and cap the attempts.

## FAQ

### A team enables strict schema enforcement. Parse errors drop to zero, but downstream reports still contain wrong severity values. What best explains this?

Grammar masking removes invalid tokens, so structure becomes deterministic. Which allowed value gets sampled is still a model judgment, and that is where semantic errors live.

### Which failure does masking the end-of-sequence token until the grammar accepts a complete document most directly prevent?

Holding end-of-sequence open until the document parses means generation cannot terminate mid-structure. Wrong values and unsupported keywords are separate problems.

### Your extraction schema nests entities three levels deep and the model keeps dropping inner items. Which change should you try first?

Deep nesting multiplies the points where a structure can be abandoned, and ending a list early is always grammatically legal. Flattening removes both risks before any sampling or retry tuning.

### Does forcing structure before a model reasons degrade extraction accuracy?

If it does, the correct architecture is a free-text reasoning pass followed by a constrained formatting pass, which changes latency, cost, and prompt design.

### How much of the residual semantic error is schema design versus model capability?

Design fixes are cheap and local; capability fixes mean changing models or adding human review, with very different cost profiles.

### Do grammar constraints interact with sampling temperature in ways that affect confidence calibration?

Sampling settings tuned on free generation may be miscalibrated under masking, which would make stated confidence systematically misleading.

---

Delve Editorial · https://delve.prisflow.com/p/structured-outputs
