Structured output prompting helps an LLM return data that an application can parse, validate, and use safely. This guide provides a reusable checklist for defining a JSON contract, writing schema-aware instructions, handling optional values, validating responses, and deciding what to do when an output is incomplete or malformed.
Overview
Asking an LLM to “return JSON” is not the same as defining a reliable data interface. A plain prompt may produce valid-looking JSON in one test and then add commentary, omit a field, change a data type, or return a different structure for an unusual input. Structured output prompting reduces that variability by combining clear instructions with an enforceable response format where the model platform supports one.
The most dependable workflow has five parts:
- Define the response contract before writing the prompt.
- Describe each field, its type, and its allowed values.
- Use a platform schema or structured-output feature when available.
- Validate the complete response in your application.
- Log, reject, or repair failures without silently accepting bad data.
Think of the prompt as documentation for the model and the schema as an interface for your software. Neither replaces application-side validation. A successful parse only proves that the text is syntactically valid; it does not prove that the values are accurate, safe, complete, or appropriate for the next step in an AI workflow.
Plain prompting, JSON mode, and structured outputs
| Approach | What it provides | Best use | Main limitation |
|---|---|---|---|
| Plain prompt | Instructions such as “return JSON only” | Prototypes, low-risk extraction, and platforms without a format control | The model may add text, omit fields, or vary the shape |
| JSON mode or equivalent | Help producing syntactically valid JSON | Applications that can perform their own schema validation | Valid JSON may still have the wrong fields, types, or values |
| Structured outputs or schema-constrained generation | A platform-enforced response shape, subject to its supported schema features | Production integrations that need predictable parsing | Support, parameter names, and schema limitations vary by model and API |
Check the documentation for the exact model and SDK you are using. API parameter names, supported JSON Schema features, refusal or error behaviour, and compatibility can change as platforms evolve. Treat the table as a design comparison, not a guarantee that every provider exposes the same controls.
Checklist by scenario
Scenario 1: Extracting fields from unstructured text
Start with the smallest useful object. If the task is to extract a person’s name, email address, and organisation, do not ask for a large profile object containing fields the source text cannot support.
- List every required field and give it a stable name.
- Choose one type per field: for example, a string, number, boolean, array, or object.
- Define what happens when a value is absent. Use a nullable field, an empty array, or an explicit status rather than leaving the choice to the model.
- Tell the model to distinguish “not mentioned” from “mentioned but uncertain” if that difference matters.
- Include the source text in a clearly marked input section and instruct the model not to invent missing values.
A practical system prompt template is:
You extract information from the supplied source text.
Return only the response object defined by the schema.
Use null when a nullable value is not present in the source.
Do not infer or invent facts. Preserve the source wording where exact text is requested.
If the source is insufficient, set the relevant status field to "insufficient_evidence".
Scenario 2: Classification or routing
Classification becomes more reliable when the allowed labels are closed rather than open-ended. Define the exact enum values and add a field for the model’s confidence or evidence only if your application has a clear use for them.
- Use an enumerated label such as
billing,technical, orother. - Explain the decision rule for borderline cases.
- Provide a short evidence array containing quoted or paraphrased input spans if review is required.
- Separate the predicted class from the action your software will take.
Do not let the model return arbitrary routing instructions in the same field that your application uses to select a tool. For high-impact actions, validate the label against an allowlist and apply business rules outside the prompt.
Scenario 3: Generating content with metadata
For a generated article outline, product description, or support response, separate the human-readable content from machine-readable metadata. A useful object might contain title, summary, sections, audience, and review_flags.
- Specify whether Markdown, HTML, or plain text is expected inside content fields.
- Set minimum or maximum lengths only when your application can enforce them consistently.
- Use arrays for repeated items rather than numbered keys such as
item_1anditem_2. - Keep review flags separate from the generated copy so they can be displayed or filtered independently.
Scenario 4: Multi-step workflows and tool use
For prompt chaining or function-calling workflows, define a narrow output for each step. One model call can extract facts, another can evaluate them, and a final step can format an approved result. Avoid asking a single response to extract data, make a decision, call a tool, and write a user-facing explanation unless there is a strong reason to combine those responsibilities.
Use the same discipline for tool arguments: define required fields, validate identifiers, and prevent free-form model text from becoming an unchecked command. See the function-calling prompt templates guide for a related approach to reliable tool use.
What to double-check
Before connecting a schema to an API integration, work through this review list.
- Field names: Are names stable, descriptive, and consistent with the consuming code? Avoid changing between
customer_id,customerId, andidwithout a migration plan. - Required fields: Does “required” mean the key must exist, or that it must contain a non-empty value? Define both expectations.
- Nullability: Decide whether an absent value is represented by
null, an empty string, an empty array, or a separate status. Use one convention. - Types: Do not describe a date as a number in one place and a string in another. If a timestamp is a string, specify the expected representation and validate it.
- Enums: Check spelling, capitalisation, and fallback labels. A single unexpected enum value can break downstream routing.
- Additional properties: Decide whether extra keys should be rejected, ignored, or retained for debugging. The platform’s schema support may affect this choice.
- Length and size: Consider limits for arrays, strings, nested objects, and overall response size. Large free-form fields are more likely to need separate handling.
- Refusals and incomplete responses: Decide how the application identifies a refusal, truncation, timeout, or provider error. Do not assume every failure is a JSON parse error.
- Semantic validation: Check that values make sense, not only that they match the type. An email-shaped string can still be unusable; a date can still be outside the permitted range.
A robust application normally follows this sequence: receive the model response, detect transport or API errors, parse the candidate JSON, validate it against the expected schema, run domain-specific checks, then either continue or return a controlled failure. Record enough diagnostic information to improve the prompt without exposing sensitive input in logs.
For a broader review of parsing, hallucination, and safety checks, use the LLM output validation checklist. Pair schema validation with test cases rather than relying on a few successful examples.
Common mistakes
“Return JSON only” is treated as a complete solution
This instruction is useful but weak on its own. It does not define fields, types, missing-value behaviour, or allowed values. Use it alongside a schema and application-side validation.
The schema is too ambitious
Deeply nested objects, many optional fields, and loosely defined free-form properties make failures harder to diagnose. Begin with a small contract and add fields only when a real use case requires them.
Optional fields have no explicit policy
If one caller receives null, another receives an omitted key, and a third receives “unknown”, downstream code becomes needlessly complicated. Choose a representation and test it.
Validation is performed only by the model
A prompt can ask the model to check its own work, but self-checking is not a substitute for deterministic validation. Keep business rules, permissions, and safety gates in application code.
Repair logic silently changes meaning
Removing a trailing comma or extracting JSON from a code fence may recover formatting. It cannot safely resolve a missing customer ID, a contradictory classification, or an unsupported action. Separate harmless formatting repair from semantic correction, and send uncertain cases to a retry or review path.
Prompt changes are not tested like code
Changes to field descriptions, examples, model settings, or provider parameters can alter output behaviour. Maintain representative fixtures, edge cases, malformed inputs, and expected validation outcomes. The LLM evaluation and prompt testing guide can help structure that process.
When to revisit
Review a structured output prompt whenever the contract or its environment changes, not only when a visible failure occurs. Revisit it in these situations:
- Before a seasonal planning cycle or any period with unusually different input volume and content.
- When you add, remove, rename, or make a field optional.
- When the model, provider, SDK, response-format parameter, or schema implementation changes.
- When a workflow moves between hosted and local models or between different model families.
- When validation failures, retries, refusals, or truncation become more frequent.
- When downstream software begins using a field for a new decision or automated action.
- When prompt instructions, few-shot examples, retrieval context, or tool definitions change.
Keep a short change record containing the schema version, prompt version, model configuration, known limitations, and test results. If a contract change is breaking, version the response or provide a migration path rather than changing the shape silently. The prompt versioning guide covers this maintenance practice in more detail, while the model migration checklist is useful when the underlying model changes.
Before shipping a new response type, confirm that the schema matches the consuming code, the prompt explains missing and uncertain values, the platform supports the schema features you rely on, and invalid or unsafe outputs have a controlled path. That checklist turns structured output prompting from a formatting preference into a maintainable reliability practice.