Reliable JSON from an LLM requires more than asking for a particular format. This guide provides reusable JSON Schema patterns for extraction, classification, nested records, and optional fields, then shows how to validate, retry, repair, and monitor responses safely in an application.
Overview
LLMs generate text, even when that text is intended to represent data. A model can add introductory prose, omit a field, return a number as a string, use invalid commas, or produce a structurally valid object with the wrong meaning. These failure modes matter when the response feeds a database, workflow automation step, API call, or content operation.
Structured outputs improve reliability by defining the shape of an acceptable response. A schema can specify required properties, data types, enumerated values, arrays, nested objects, and whether additional properties are allowed. It does not remove the need for application-side validation: the schema checks structure, while your code must still check business rules, permissions, source quality, and model behavior.
A practical LLM JSON workflow has five stages:
- Define the smallest useful output schema.
- Tell the model what each field means and what to do when information is missing.
- Request structured output using the capabilities of the selected API or SDK.
- Parse and validate the response before using it.
- Retry, repair, or route the case for review when validation fails.
Provider syntax and supported JSON Schema features vary, so treat the patterns below as portable design examples rather than a guaranteed API payload. Check the documentation for the model and integration you are using before production deployment.
Template structure
A dependable JSON extraction prompt separates instructions, source content, and the output contract. Keep those parts explicit and version them together.
System instruction:
Return one JSON object matching the supplied schema.
Do not include Markdown, commentary, or additional keys.
Use null when a field cannot be supported by the source text.
Do not guess facts that are absent from the source.
Task:
Extract the requested fields from the source text.
Source:
{{source_text}}
Output contract:
{{json_schema}}
The system instruction establishes the response boundary. The task describes the operation, while the source is clearly delimited as untrusted input. The schema supplies machine-readable constraints. This separation also makes prompt testing easier because you can change the source examples without rewriting the contract.
Basic extraction schema
{
"type": "object",
"properties": {
"title": { "type": "string" },
"summary": { "type": "string" },
"language": { "type": "string" }
},
"required": ["title", "summary", "language"],
"additionalProperties": false
}
Use required fields when downstream code expects them on every successful response. If the source may not contain a value, a nullable field or an explicit status value is usually safer than silently inventing content. Define that behavior in both the schema and the prompt.
Classification schema
{
"type": "object",
"properties": {
"label": {
"type": "string",
"enum": ["bug", "feature_request", "question", "other"]
},
"confidence": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"reason": { "type": "string" }
},
"required": ["label", "confidence", "reason"],
"additionalProperties": false
}
An enum limits labels to values your application understands. A confidence value can be useful for routing, but it is not proof that the classification is correct. Set a review threshold through testing rather than assuming that a particular number has universal meaning.
Nested records and arrays
{
"type": "object",
"properties": {
"customer_id": { "type": "string" },
"contacts": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": { "type": "string" },
"email": { "type": "string" },
"role": { "type": "string" }
},
"required": ["name", "email", "role"],
"additionalProperties": false
}
}
},
"required": ["customer_id", "contacts"],
"additionalProperties": false
}
Nested schemas are useful for invoices, support tickets, product records, and other documents with repeating entities. Keep each object focused. A large schema with many optional branches is harder to validate, test, and recover than several smaller extraction steps.
How to customize
Start with the consumer of the JSON, not with the prompt. List the fields that the next system actually needs, then choose types and constraints that match that system.
- Use stable field names: Choose one naming convention, such as snake_case, and preserve it across versions.
- Describe semantics: Explain whether a date is an event date, publication date, or due date. A type alone cannot resolve ambiguity.
- Choose a missing-value policy: Use null, an empty array, an explicit unknown label, or a validation failure deliberately. Do not leave the model to infer the policy.
- Constrain enumerations: Use enum values for routing states, categories, priorities, and other controlled vocabularies.
- Limit extra keys: Disallow additional properties where your integration expects a fixed contract. If provider support differs, enforce the same rule in application validation.
- Keep instructions near edge cases: State how to handle conflicting evidence, duplicate records, truncated text, and unsupported values.
For long documents, consider a staged workflow: identify relevant passages, extract records from those passages, then normalize and validate the records. This prompt chaining pattern can be easier to debug than asking for every field and transformation in one call. It can also make provenance more visible if each record includes a source quote or location.
Do not place secrets, access tokens, or unnecessary personal data in a prompt merely to satisfy a schema. Structured output controls shape, not data protection. For applications that accept user-controlled text, isolate instructions from the data and review prompt injection prevention patterns.
Examples
Validation and recovery workflow
Parsing and schema validation should occur before the response reaches business logic. A simple implementation can follow this sequence:
- Capture the raw model response and request metadata for debugging, subject to your data-retention rules.
- Remove no content automatically unless the API contract explicitly permits it. Parse the response as JSON.
- Validate the parsed value against the expected schema.
- Run domain checks, such as valid identifiers, permitted transitions, date relationships, or required source evidence.
- If the failure is recoverable, send a focused retry containing the validation error and the original task.
- After a bounded number of attempts, return a controlled failure or send the item to human review.
A retry prompt should not simply say “try again.” Include the specific problem, such as “contacts must be an array of objects” or “priority must be one of the listed enum values.” Keep the original source available, and ask for the complete corrected object rather than a partial patch unless your parser explicitly supports patches.
For deterministic formatting failures, a local repair step may be appropriate, but it should never turn an invalid or ambiguous answer into an apparently trusted record without revalidation. After repair, parse and validate again. For a broader treatment of parsers, retries, and recovery, see the LLM output validation guide.
Troubleshooting table
| Failure | Likely cause | Practical response |
|---|---|---|
| JSON parse error | Markdown fences, commentary, truncated output, or invalid commas | Use native structured output where available, reduce output size, and reject or retry malformed responses. |
| Missing required field | The field is difficult to infer or the instruction is ambiguous | Define a missing-value policy and explain the field’s meaning with a representative example. |
| Wrong data type | The model treats formatting as natural language | State the type, validate it in code, and use a schema-enforced response mode when supported. |
| Unexpected property | The model adds helpful but unsupported metadata | Disallow extra properties and make the no-commentary rule explicit. |
| Valid JSON, wrong meaning | The object satisfies structure but not the task | Add semantic checks, source evidence, test cases, and a review route for low-confidence results. |
| Inconsistent enum values | Synonyms or capitalization vary across examples | Provide the exact allowed values and normalize only through an explicit, tested rule. |
Build a small test set containing ordinary inputs, empty inputs, conflicting statements, long inputs, multilingual text when relevant, and adversarial instructions embedded in the source. Track parse success, schema success, semantic accuracy, retry rate, latency, and cost. The LLM evaluation checklist can help organize regression tests as prompts and models change.
When to update
Revisit a structured-output template whenever its contract, inputs, model, or downstream workflow changes. A working prompt is not a permanent guarantee: a provider may change supported schema features, your SDK may alter request syntax, or a new source format may introduce cases your original tests did not cover.
Update the schema and tests when you add or rename fields, change enum values, alter null handling, introduce nested records, or modify the system that consumes the response. Re-test when changing the model, temperature or sampling settings, context assembly, retrieval method, or maximum output limit. Also revisit the template after repeated validation failures, unexplained shifts in classification, or an increase in manual review.
Keep a versioned record of the schema, prompt instructions, model configuration, representative test inputs, validation rules, and known limitations. Log which version produced each record. When a contract change is breaking, consider accepting both versions temporarily and migrating records explicitly rather than silently changing the meaning of existing data. For operational signals such as failure rates and latency, see the AI workflow observability guide.
To put this pattern into practice, choose one narrow extraction task today. Write its schema, add five ordinary examples and five edge cases, validate every response locally, and define a bounded retry path. Once the workflow is stable, store the prompt and schema in a version-controlled template library and add it to your regular prompt testing cycle. That small loop—contract, test, validate, observe, update—does more to produce reliable JSON than adding longer instructions alone.