Developer reviewing JSON schema fields on a monitor beside a terminal

Structured JSON Outputs from LLMs: Schemas That Stick

Structured JSON outputs mean the model is constrained to emit text that parses as JSON and matches a schema you supply. When the provider enforces that constraint during decoding, malformed braces and missing required keys stop being a retry problem. They do not make the content true, and they do not remove refusals, truncation, or business-rule violations. That gap is where most production incidents live.

This guide walks through what the guarantee covers, how to shape schemas so they survive real inputs, and what to validate afterwards. Examples use invoice and support-ticket extraction because they fail in instructive ways. If you are still deciding whether to prompt, fine-tune, or retrieve, start with RAG vs fine-tuning vs agents; if your outputs feed tools, read MCP vs API function calling alongside this.

What a schema guarantee actually buys you

OpenAI’s documentation states the contract plainly: Structured Outputs constrains completed, non-refusal output to your JSON Schema, and your application still has to handle refusals, incomplete responses, and API errors, plus any business rules the schema cannot express (OpenAI structured outputs guide). Anthropic describes the same idea as grammar-constrained decoding and calls out two stop reasons you must branch on: refusal and max_tokens (Claude structured outputs docs).

Read that sentence twice. A schema can promise that total is a number. It cannot promise that the number equals the sum of the line items, that currency matches the document, or that a date is not invented because the source was blank. Treat schema compliance as syntax insurance, then add semantic checks yourself.

Prompt-only, JSON mode, and constrained decoding are different tools

Teams often say “we use JSON” when they mean three very different things. The table below keeps the options honest.

ApproachWhat it enforcesTypical failureUse when
Prompt says “reply in JSON”NothingProse before the JSON, trailing commentary, wrong keysThrowaway prototypes only
JSON modeValid JSON syntaxValid JSON that ignores your schemaLegacy models without schema support
Schema-constrained outputs (strict / output_config.format)Syntax plus keys, types, required fields, enumsRefusal, truncation, plausible-but-wrong valuesDefault for new extraction and routing code
Self-hosted grammar decoding (Outlines, llguidance-style engines)Token-level grammar on your own inference stackLatency and schema compile costOpen-weight models you serve yourself

OpenAI recommends Structured Outputs over JSON mode whenever possible because JSON mode only guarantees parseable JSON, not adherence to your fields. For open-weight models served locally, libraries such as Outlines apply the same idea at the sampler. If you stay in Python and want typed retries across providers, Instructor wraps Pydantic models around many client SDKs.

Design the schema for the worst input, not the demo input

Most schema bugs are product bugs wearing a JSON costume. A field marked required forces the model to answer even when the document is silent. The model complies, and you get a confident hallucination that parses perfectly.

  • Give every uncertain field an escape hatch. Use a nullable type or an enum value such as "not_stated". OpenAI requires all fields to be listed as required in strict mode, so optionality is expressed as a union with null.
  • Prefer enums over free text for routing decisions. A priority enum of low | normal | urgent is testable. A free-text priority is a regex project waiting to happen.
  • Put reasoning where it cannot corrupt the payload. A short evidence_quote string per extracted field lets you verify values against the source later. Avoid asking for long step-by-step reasoning inside a strict schema; Claude’s docs note that fields requesting the model’s thinking can trigger a reasoning_extraction refusal.
  • Flatten before you nest. OpenAI documents limits of 5,000 object properties and 10 nesting levels. You will rarely hit them, but deeply nested schemas are also harder to debug and to write evals for.
  • Use descriptions as tiny prompts. A description like “ISO 4217 code, uppercase” on currency does more work than a paragraph in the system message.

Property order matters too. OpenAI notes that outputs follow the key order in your schema, so put evidence_quote before value if you want the model to ground itself first, and put confidence last.

A schema you can copy and then break on purpose

Here is a Pydantic model for invoice extraction. It is deliberately small. Every field that can be absent is nullable, and the verdict about extraction quality is its own enum rather than a vibe in a string.

from enum import Enum
from pydantic import BaseModel, Field

class Currency(str, Enum):
    USD = "USD"
    EUR = "EUR"
    KRW = "KRW"
    OTHER = "OTHER"

class LineItem(BaseModel):
    description: str
    quantity: float | None = Field(description="null if not stated")
    unit_price: float | None
    evidence_quote: str = Field(description="verbatim text from the document")

class Invoice(BaseModel):
    vendor_name: str | None
    invoice_date: str | None = Field(description="YYYY-MM-DD or null")
    currency: Currency
    line_items: list[LineItem]
    stated_total: float | None
    extraction_status: str = Field(
        description="one of: complete, partial, unreadable"
    )

Notice what is missing: no minimum on stated_total, no maxLength on strings. Several providers reject or ignore those keywords in strict mode. Claude’s documentation lists numerical and string-length constraints as unsupported for its grammar, and OpenAI lists some of them as unsupported for fine-tuned models. Keep range checks in the validation layer described next.

Validate after the model, in layers

A reliable pipeline treats the model response like any other untrusted input: parse, then validate shape, then validate meaning, then decide what to do on failure.

  1. Branch on completion state first. Check the refusal indicator and the stop reason before touching the payload. A truncated JSON object that happens to close its braces is still a truncated answer.
  2. Parse into a typed object. Pydantic, Zod, or your language’s equivalent. Do not pass raw dictionaries around.
  3. Run semantic checks. For invoices: line items multiplied out should land within a tolerance of stated_total; the date should not be in the future; the currency should be one your ledger supports.
  4. Verify evidence quotes. Search the source text for each evidence_quote. A value with no matching quote gets flagged for review, even if it parses.
  5. Decide the failure policy per field. Some failures retry with a clearer instruction, some route to a human queue, some degrade to a partial record with extraction_status set accordingly.

Anthropic’s docs describe a subtler trap worth testing explicitly: enum matching can differ in capitalization from your schema values without any error or special stop reason, so compare enum values case-insensitively or normalize them before branching. Cheap to handle, expensive to discover in production.

Failure modes we see after the first week

Valid, confident, wrong

The classic: a required vendor_name on a scanned receipt with no header yields the name of a product printed in large type. The fix is not a stricter schema, it is a nullable field plus an evidence quote and a spot-check sample reviewed weekly.

Truncation on long documents

Long line-item lists can hit the output token limit mid-array. Providers surface this as a stop reason, not as invalid JSON, because the constrained output is still grammatical up to the cut. Set max_tokens from the input size, chunk big documents, and alert when the stop reason is anything other than a clean finish.

Schema drift between prompt and code

Someone adds a field to the Pydantic class and forgets that a few-shot example in the system prompt shows the old shape. Generate examples from the schema, or at least test that every example validates against the current model.

Enum creep

Product adds a new ticket category. The schema is updated, the downstream router is not. Version your schema, log the version in every trace, and treat enum additions as a breaking change for consumers.

Testing structured outputs without a giant eval platform

Start with thirty to fifty real inputs, including ugly ones: blurry scans, empty fields, two currencies on one page, a document in the wrong language. For each, store the expected JSON. Run the extraction in CI and report field-level accuracy, not a single pass or fail. When you are ready for something more formal, golden datasets for LLM apps covers versioning, and the promptfoo evaluation guide shows how to wire assertions into a pipeline.

Field-level reporting matters because aggregate accuracy hides the one field that carries the money. A pipeline that gets vendor names right 99 percent of the time and totals right 91 percent of the time is not a 95 percent system; it is a system with a totals problem.

Rollout plan for a new extraction endpoint

  1. Ship with schema-constrained outputs and a nullable-by-default design, behind a feature flag.
  2. Log the schema version, model name, stop reason, validation result, and token counts per request. The observability stack for LLM apps article lists the minimum trace fields.
  3. Sample five to ten percent of outputs for human review in week one. Track which fields reviewers correct.
  4. Add semantic validators for the top two correction categories. Re-run your fixed test set.
  5. Only then widen traffic. Put a regression gate in front of schema or prompt changes using ideas from eval regression gates.

If your extraction output triggers actions, such as refunds or database writes, keep a deterministic policy layer between the JSON and the action. The patterns in the agent permissions model apply even when the “agent” is a single function call.

Bottom line: pick schema-constrained decoding as your default, design for missing data, branch on stop reasons, and validate meaning outside the model. Schemas stick when they describe reality, including the parts of reality your documents leave blank.

FAQ

Are structured JSON outputs the same as JSON mode?

No. JSON mode guarantees the response parses as JSON but not that it matches your fields. Schema-constrained structured outputs enforce keys, types, required fields, and enums as well. Prefer the schema-constrained option when your model and provider support it.

Do structured outputs stop hallucinations?

No. They stop syntax and shape errors. A model can still return a perfectly valid object containing a wrong or invented value. Use nullable fields, evidence quotes, and semantic validators to catch the content errors a schema cannot see.

What should I do when the model refuses or hits the token limit?

Check the refusal indicator and the stop reason before reading the payload. Treat refusals as a distinct outcome with a fallback path, and treat a max-tokens stop as an incomplete answer even if the JSON looks closed. Increase the limit or chunk the input.

How do I represent optional fields in strict mode?

OpenAI’s strict mode requires every field to be listed as required, so you model optional values as a union with null. For other providers, check the schema limitations page, because some also require additionalProperties to be false on every object.

Should I put validation rules like min and max in the JSON schema?

Only if your provider supports them. Several strict-mode implementations reject or ignore numeric ranges and string length keywords. Put those rules in a Pydantic or Zod layer after the response so they work on every provider.

Can I get structured outputs from open-weight models?

Yes. Inference engines and libraries such as Outlines apply grammar-constrained decoding at the sampler, so a self-hosted model can be forced to match a schema. Expect extra latency when schemas are large or compile slowly, and test on your own documents.

Related reading

About Mudasir Syed

Check Also

Engineer reading a deep learning book beside a laptop showing a training loop and loss curve

fast.ai Practical Deep Learning for LLM Builders

Most people building LLM applications never train a network, so a classic deep learning course …

Leave a Reply