Reliable extraction from an LLM requires more than asking for JSON. This guide compares structured-output approaches, provides reusable JSON Schema patterns for invoices, contact records, and support tickets, and shows how to validate structure separately from factual accuracy.
Overview
LLM structured outputs are a way to constrain a model’s response to a machine-readable shape. Instead of receiving a paragraph that a developer must interpret, an extraction request can target an object with defined fields, types, allowed values, nested objects, and arrays. This is useful when model output feeds a database, workflow, search index, API response, or downstream automation.
There are three related but different techniques:
- Prompted JSON: The prompt asks the model to return JSON, but the application must assume that formatting can fail.
- JSON mode: A provider-level setting may encourage valid JSON, but it does not necessarily enforce the exact fields, types, or constraints your application needs.
- Schema-constrained structured output: The request includes a schema that the provider and model use to constrain the response. Support for keywords, strictness, refusals, and SDK configuration varies by provider and API version.
A schema improves the shape of the response; it does not prove that the extracted values are correct. For example, a value such as 2025-02-30 may match a date-like string pattern while still being invalid, and a model can place the wrong total in a correctly typed number field. Treat structural validation and factual validation as separate stages.
Before implementing an integration, check the current documentation for the provider and model you plan to use. Confirm supported schema keywords, whether additional properties are allowed, how nullable values are represented, how refusals are returned, and what happens when a response is cut off. These details can change independently of your extraction prompt.
How to compare options
Compare structured-output approaches against the failure modes that matter in your application rather than choosing based only on a feature label. A useful evaluation covers five questions.
- Can the response be parsed? Test malformed JSON, surrounding commentary, markdown fences, and empty responses. A parser failure should produce a controlled application error, not an unhandled exception.
- Does the shape match? Validate required fields, data types, enums, array items, nested objects, and whether unknown properties are accepted or rejected. Use the same validation library in development and production when practical.
- Does the content match the source? Compare extracted values with labeled examples. A schema validator can confirm that
totalis a number, but not that it is the invoice total rather than a subtotal. - What happens when information is absent? Decide whether a missing value should be
null, an empty array, a status such asunknown, or an explicit error. Do not leave this decision to inconsistent model interpretation. - How does the integration fail? Test refusals, content filtering outcomes, timeouts, rate limits, truncated output, provider errors, and schema incompatibilities. Each case should have a distinguishable result for logging and retry logic.
The following reference table helps turn schema design into an explicit decision:
| Requirement | Schema pattern | Application decision |
|---|---|---|
| Always needed | Required property | Reject or route for review when absent |
| May be missing in the source | Nullable value or documented sentinel | Use one consistent missing-data convention |
| Limited set of states | Enum | Map unknown source wording to an allowed state or review queue |
| Repeated values | Array with an item schema | Define whether an empty array means “none found” |
| Related fields | Nested object | Validate the object and its internal required fields |
| Unexpected keys | Provider-specific additional-property behavior | Verify support and decide whether to reject or preserve them |
When comparing providers or models, run the same golden dataset through each option. Measure parse success, schema validation success, field-level accuracy, refusal handling, latency, and cost under your own workload. The LLM Golden Dataset Guide can help you organize reusable test cases, while the Prompt Evaluation Framework covers broader evaluation design.
Feature-by-feature breakdown
Invoice extraction
Invoices combine scalar fields, optional values, and repeated line items. A practical baseline schema might look like this:
{
"type": "object",
"properties": {
"invoice_number": { "type": ["string", "null"] },
"invoice_date": { "type": ["string", "null"] },
"due_date": { "type": ["string", "null"] },
"vendor": {
"type": "object",
"properties": {
"name": { "type": ["string", "null"] },
"tax_id": { "type": ["string", "null"] }
},
"required": ["name", "tax_id"]
},
"currency": { "type": ["string", "null"] },
"line_items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"description": { "type": "string" },
"quantity": { "type": ["number", "null"] },
"unit_price": { "type": ["number", "null"] },
"line_total": { "type": ["number", "null"] }
},
"required": ["description", "quantity", "unit_price", "line_total"]
}
},
"subtotal": { "type": ["number", "null"] },
"tax": { "type": ["number", "null"] },
"total": { "type": ["number", "null"] }
},
"required": ["invoice_number", "invoice_date", "due_date", "vendor", "currency", "line_items", "subtotal", "tax", "total"]
}
Keep monetary values consistent. Decide whether your application expects decimal numbers, integer minor units, or strings, then validate and normalize at the application boundary. Also validate arithmetic relationships where appropriate: line totals, subtotal, tax, and total should be compared with a defined tolerance rather than trusted because they fit the schema.
Contact record extraction
Contact data often contains genuinely absent values. A schema can require a stable object while allowing individual fields to be null:
{
"type": "object",
"properties": {
"full_name": { "type": ["string", "null"] },
"job_title": { "type": ["string", "null"] },
"organization": { "type": ["string", "null"] },
"emails": { "type": "array", "items": { "type": "string" } },
"phone_numbers": { "type": "array", "items": { "type": "string" } },
"addresses": {
"type": "array",
"items": {
"type": "object",
"properties": {
"kind": { "type": ["string", "null"] },
"formatted": { "type": "string" }
},
"required": ["kind", "formatted"]
}
}
},
"required": ["full_name", "job_title", "organization", "emails", "phone_numbers", "addresses"]
}
Do not use an empty string and null interchangeably. An empty array can mean that no items were found, while a null field can mean that the field is not present or cannot be determined. Define that meaning in your application contract and document it for consumers.
Support ticket classification
Support tickets benefit from enums because downstream routing usually depends on a controlled vocabulary:
{
"type": "object",
"properties": {
"summary": { "type": "string" },
"category": {
"type": "string",
"enum": ["billing", "technical", "account", "security", "other"]
},
"priority": {
"type": "string",
"enum": ["low", "normal", "high", "urgent"]
},
"sentiment": {
"type": "string",
"enum": ["negative", "neutral", "positive", "unclear"]
},
"requires_human_review": { "type": "boolean" },
"reason": { "type": ["string", "null"] }
},
"required": ["summary", "category", "priority", "sentiment", "requires_human_review", "reason"]
}
Enums reduce downstream variation, but they do not make classification correct. Test ambiguous tickets, multiple issues in one message, missing context, and adversarial text. If ticket content may contain instructions aimed at the model, treat it as untrusted data and apply the controls described in Prompt Injection Defense for LLM Apps.
Missing data, refusals, and truncation
Use an explicit response-processing pipeline:
- Check the provider response status and refusal or safety fields before parsing the output.
- Check whether the generation ended normally or was cut off. A partial object should not be treated as a complete extraction.
- Parse the response as JSON using a strict parser.
- Validate it against the intended schema.
- Run semantic checks such as date validity, arithmetic reconciliation, identifier formats, and source-grounded field checks.
- Store the original input, schema version, model configuration, validation result, and review decision according to your privacy and retention requirements.
For a refusal, return a distinct application state such as refused; do not convert it into an object filled with nulls. For truncation, retry only when the cause and retry policy are understood. If the input is too large, reducing irrelevant context or extracting in stages may be safer than repeatedly requesting the same output.
Best fit by scenario
- Prototype or internal script: Prompted JSON plus local parsing may be adequate while the data contract is still changing. Add schema validation before the script affects production records.
- Stable production extraction: Prefer provider-supported structured outputs when their constraints match your schema. Keep application-side validation because structural guarantees do not establish factual accuracy.
- Provider migration: Keep a provider-neutral schema and a separate adapter for request configuration, response parsing, refusal handling, and supported keywords. Do not assume identical behavior across OpenAI, Claude, Gemini, or other APIs.
- High-consequence decisions: Require semantic checks, confidence or evidence fields where useful, human review, and an audit trail. A valid JSON response is not authorization to automate an irreversible action.
- Large or complex documents: Extract in bounded stages, such as document metadata, line items, and totals, then reconcile the results. This can make failures easier to locate than one large schema.
Model selection still matters. A smaller or faster model may be suitable for predictable fields, while a more capable model may handle noisy documents or ambiguous language better. Compare models on your own labeled examples rather than assuming that a schema alone will remove quality differences. For broader selection criteria, see LLM Model Comparison for Developers.
When to revisit
Revisit a structured-output integration whenever its inputs, schema, model, or provider behavior changes. A practical maintenance schedule includes these triggers:
- A database field is renamed, split, removed, or changed from optional to required.
- A new document type, language, vendor format, or support category is introduced.
- The model, API version, SDK, system prompt, temperature-related setting, or output configuration changes.
- Provider documentation changes supported schema keywords, strictness settings, refusal representation, or truncation behavior.
- Validation failures, corrected records, or human-review patterns reveal a new extraction error.
- Privacy, retention, security, or compliance requirements change.
Keep a versioned schema and a small regression set containing ordinary examples, missing fields, conflicting values, long inputs, malformed source text, refusal-prone requests, and boundary cases. Run it before deployment and after provider releases. Track structural validity separately from field accuracy, because an integration can improve on one measure while regressing on the other.
Finally, document the contract in the codebase: the meaning of nulls and empty arrays, accepted enum values, numeric conventions, retry behavior, and the human-review path. When you need to debug a failed extraction, the Prompt Troubleshooting Cookbook, Prompt Versioning Workflow, and Developer Utility Toolkit provide useful adjacent practices. The result is not merely valid JSON, but a maintainable data boundary that can be tested as your application evolves.