Reliable JSON from an LLM requires more than adding “return valid JSON” to a prompt. This guide explains how to choose between JSON mode, structured outputs, function calling, and plain prompt formatting, then shows how to define a schema, validate every response, and recover safely when a model returns malformed or incomplete data.
Overview
Structured outputs are a design pattern for making an LLM response usable by software. Instead of treating the model’s answer as free-form text, your application defines the expected fields, types, required values, and constraints. The model then produces data that can be parsed and checked before it reaches a database, user interface, workflow, or downstream API.
There are four common ways to request JSON from a model:
| Approach | What it provides | Best use | Main limitation |
|---|---|---|---|
| Plain prompt formatting | Instructions such as “return only JSON” | Prototypes, low-risk experiments, or providers without structured features | The model can still add prose, omit fields, or produce invalid syntax |
| JSON mode | Generally valid JSON output | Simple responses where syntax matters more than exact structure | Valid JSON does not guarantee the required fields or correct data types |
| Structured outputs | A provider-enforced or provider-guided schema | Extraction, classification, routing, and production workflows | Schema features and supported keywords vary by model and SDK |
| Function calling or tool calling | Arguments matching a declared function or tool definition | Applications that need a controlled action or typed payload | The application must still validate arguments and decide whether to execute the tool |
These approaches are not interchangeable. JSON mode can prevent a trailing explanation while still allowing a response such as {"items":"none"} when your application expects an array. A schema or function definition communicates the shape more precisely, but it does not remove the need for validation, error handling, and business rules.
For broader prompt engineering guidance, see the guide to zero-shot and few-shot prompting frameworks. If your task involves extracting fields from documents, the data extraction prompt template guide provides a useful companion pattern.
Checklist by scenario
Scenario 1: You need a simple JSON object
Start with a small schema and a narrow task. Define the expected keys, allowed values, and treatment of missing information. Do not ask the model to infer a complete record when the source text does not contain the answer.
{
"type": "object",
"properties": {
"summary": { "type": "string" },
"priority": { "type": "string", "enum": ["low", "medium", "high"] },
"confidence": { "type": "number" }
},
"required": ["summary", "priority", "confidence"],
"additionalProperties": false
}
- Use an object rather than an unstructured paragraph.
- Use enums for finite categories such as priority or status.
- Specify whether a missing value should be
null, an empty array, or a documented fallback. - Set a confidence field only when your application has a clear interpretation for it; a model-generated number is not automatically a calibrated probability.
Scenario 2: You are extracting repeated records
Use an array of objects when the input may contain multiple entities. Keep each record independent so one incomplete item does not force the model to distort the others.
{
"type": "object",
"properties": {
"people": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": { "type": "string" },
"email": { "type": ["string", "null"] },
"source_quote": { "type": ["string", "null"] }
},
"required": ["name", "email", "source_quote"],
"additionalProperties": false
}
}
},
"required": ["people"],
"additionalProperties": false
}
A source quote or source span can make review easier. It also gives you a way to distinguish extraction from invention: if the value cannot be supported by the input, return null and flag the record for review.
Scenario 3: The response should trigger an action
Use function calling or tool calling when the model needs to propose an operation such as creating a ticket, searching a catalog, or updating a record. Treat the tool call as a request, not authorization. Your application should verify the arguments, enforce permissions, and decide whether confirmation is required.
A safe function-calling checklist is:
- Define only the fields the tool actually needs.
- Constrain identifiers, dates, quantities, and enum values.
- Reject unknown properties where the provider and schema support that rule.
- Re-check authorization and business rules outside the model.
- Log the validated request and the execution result separately.
Scenario 4: The provider does not support schemas
Use a plain prompt as a fallback, but compensate with strict application checks. Put the output contract near the task instructions, show a small example when the format is unfamiliar, and request no markdown fences or explanatory text. Then parse the response, validate it, and send failures through a bounded recovery path.
Few-shot examples can help with ambiguous labels or nested fields. They should demonstrate edge cases, not just ideal inputs. The examples must agree with the schema; contradictory examples teach the model the wrong contract.
What to double-check
Before shipping an LLM structured-output workflow, review these five layers.
1. The contract
Confirm that every required field has a defined type and meaning. Decide whether dates use a single format, whether strings may be empty, and whether unknown values are rejected or represented explicitly. Keep names stable and avoid changing a field from a scalar to an array without a migration plan.
2. Provider and SDK behavior
Check the documentation for the specific model and SDK version you are using. Structured-output support, nesting limits, nullable types, required fields, additional-property rules, and refusal behavior can differ. Do not assume that a feature available in one model or endpoint works identically elsewhere. Record the model, API version, schema version, and SDK version with test results.
3. Validation
Use two kinds of validation. Syntactic validation checks whether the response can be parsed as JSON. Structural validation checks the schema. Semantic validation checks application rules such as whether a date is in an acceptable range, an identifier exists, or a total equals the sum of its line items.
4. Token and truncation handling
Large inputs and verbose fields increase the chance of incomplete output. Limit unnecessary source text, request concise values, and reserve enough output capacity for the largest expected response. Treat an incomplete response as a failure rather than attempting to silently repair a truncated object.
5. Observability and privacy
Capture validation failures, field-level error types, latency, retry counts, and model or prompt versions. Avoid logging sensitive source material unless your retention and access controls permit it. For workflows involving personal information, use the AI application data privacy checklist to review redaction, retention, and vendor considerations.
Recovery pattern for malformed responses
A reliable recovery workflow separates parsing, validation, and retry decisions:
- Parse once. Remove no content automatically unless your contract explicitly permits a safe normalization step. If parsing fails, store the failure category and response metadata.
- Validate the parsed value. Run schema validation, then semantic checks. Return field-specific errors such as “priority is not an allowed value” rather than a generic failure.
- Classify the error. A transient service failure, truncated output, schema mismatch, and unsupported request require different responses.
- Retry with a focused correction. Include the validation errors and the original task context, but avoid endlessly repeating the same prompt. A single repair attempt may be appropriate for low-risk extraction; sensitive or high-impact actions may require human review instead.
- Use a fallback. Route repeated failures to a queue, return a typed error to the caller, or use a simpler extraction path. Never execute an unvalidated tool call merely because it resembles valid JSON.
Keep repair attempts bounded and observable. A response that parses successfully after a retry should still be counted as a quality signal, because rising repair rates can indicate a prompt change, model migration, input shift, or schema problem.
Common mistakes
- Confusing valid JSON with correct data. A syntactically valid object may have missing fields, wrong types, or invented values.
- Making the schema too broad. Optional fields and unrestricted strings give the model more ways to produce inconsistent results. Start with the smallest useful contract.
- Using prose rules instead of enforceable constraints. “Use one of these three statuses” is weaker than an enum when an enum is available.
- Parsing with regular expressions. JSON is nested and escaped; use a JSON parser and a schema validator rather than extracting fragments with patterns.
- Trusting tool arguments automatically. Function calling controls format, not permission, truth, or business correctness.
- Changing schemas without versioning. Store a schema version and test old and new consumers before rollout.
- Retrying without diagnosing. Repeating an identical request can add cost and latency without improving reliability.
When to revisit
Review this design whenever you add an extraction field, change a schema, introduce a new model, update an SDK, switch providers, or see a change in parsing or validation failures. Also revisit it before seasonal planning cycles or other periods when input volume and document types change. A workflow that passed tests on short, clean examples may behave differently when inputs become longer, multilingual, or less structured.
Keep a compact regression set containing normal inputs, missing values, conflicting facts, long inputs, malformed source text, multiple records, and adversarial instructions embedded in the source. Run it after prompt, schema, model, or dependency changes. For untrusted documents, pair output validation with input-isolation practices from the prompt injection defense guide.
Your practical pre-release checklist is simple: choose the narrowest suitable output method, define and version the schema, validate syntax and meaning, test failure cases, bound retries, protect sensitive data, and record enough metadata to diagnose changes. If the model cannot satisfy the contract consistently, reduce the task, improve the source preparation, or add a human checkpoint instead of weakening the validation layer.