Reliable JSON from an LLM requires more than asking for “JSON only.” This guide provides a reusable structured output prompt, schema examples, validation steps, and troubleshooting advice for ChatGPT, Claude, Gemini, and API-based models.
Overview
LLMs generate language, not database records. Even when a model understands your requested format, it may add an introduction, omit a field, use inconsistent types, or place malformed text inside a nested object. These failures become especially costly when an application sends the response directly to a parser, database, workflow, or publishing system.
The most dependable approach combines four layers:
- A precise task: explain what information to extract or create.
- A defined structure: show the required fields, types, allowed values, and nesting.
- Platform controls: use a native structured-output or schema-enforcement feature when the model and API support one.
- Application validation: parse and validate the response before using it.
Prompt engineering improves the model’s behavior, but a prompt is not a substitute for validation. Treat every model response as untrusted input, including output from a model that usually behaves consistently.
For a practical workflow, start with the JSON Formatter and Validator Guide when you need to inspect a failing response. If the problem is broader than formatting, the Prompt Debugging Checklist can help isolate whether the task, context, schema, or model settings are responsible.
Checklist by scenario
1. Basic extraction from text
For a simple extraction task, define the output contract before adding examples. Tell the model what to return, what to do when information is absent, and whether extra keys are allowed.
Return one JSON object matching this structure:
{
"title": "string",
"author": "string or null",
"published_date": "YYYY-MM-DD or null",
"topics": ["string"]
}
Rules:
- Return valid JSON only. Do not use Markdown fences or explanatory text.
- Use null when a value is not present or cannot be determined.
- Use an empty array when no topics are found.
- Do not invent missing values.
- Use the exact field names and data types shown above.This pattern handles several common ambiguities. It distinguishes a missing scalar value from an empty list, establishes a date format, and prevents the model from silently filling gaps with guesses.
2. Classification with controlled values
When the output drives routing or analytics, constrain categories explicitly. A free-form label such as “high priority” can become “urgent,” “High,” or “important” across requests.
Return valid JSON only:
{
"category": "billing | technical | account | other",
"priority": "low | medium | high",
"reason": "string"
}
Choose exactly one value for category and priority. If the message does not clearly fit a category, use "other". Keep reason under 30 words and base it only on the supplied message.If your API supports an enumeration in its schema, define the allowed values there as well as in the prompt. Duplication is useful here: the schema provides a machine-readable constraint, while the prompt explains how to apply it.
3. Nested objects and repeated records
Nested JSON needs explicit instructions about cardinality. State whether a field is one object, an array of objects, or optional.
Return an object with this shape:
{
"document": {
"language": "string",
"summary": "string"
},
"entities": [
{
"name": "string",
"type": "person | organization | location | other",
"mentions": ["string"]
}
]
}
Use an empty entities array when no entities are found. Each entity must include all three fields. Do not merge separate entities into one object.For production extraction, test repeated records, no-record cases, duplicate mentions, and unusually long source text. A schema that works for one example may still fail at the edges.
4. Content operations and publishing workflows
Publishers often need structured results from an unstructured brief: a headline, summary, claims to verify, and metadata. Separate generated suggestions from verified facts so downstream users do not mistake one for the other.
Return valid JSON only:
{
"headline": "string",
"summary": "string",
"claims_for_review": [
{
"claim": "string",
"needs_source": true
}
],
"keywords": ["string"]
}
Do not mark a claim as verified. Put any factual statement that requires checking in claims_for_review. Use an empty array when no reviewable claims are present.For a wider editorial process, see the AI Content Workflow for Publishers and the AI Citation and Claim Verification Checklist.
What to double-check
Before connecting an LLM response to an application, run through this validation checklist:
- Parsing: Can your JSON parser read the complete response without trimming or manual repair?
- Top-level shape: Is the result an object or array as expected?
- Required fields: Are mandatory keys always present?
- Data types: Are numbers returned as numbers rather than quoted strings? Are booleans genuine
trueorfalsevalues? - Null policy: Does your application accept
null, or should absent values use another representation? - Allowed values: Are categories, statuses, and language codes restricted to known values?
- Additional keys: Should unexpected fields be rejected, ignored, or logged?
- String safety: Can quotes, line breaks, backslashes, and Unicode characters appear without breaking parsing?
- Length limits: What should happen if a summary, label, or array exceeds its allowed size?
- Failure handling: Does the application retry, request a repair, send the item to review, or stop safely?
Use native structured-output controls or JSON schema support when available, but confirm which schema features the selected model and platform actually support. Capabilities can differ between chat interfaces, hosted APIs, model versions, and open-source deployments. Keep the schema conservative until you have tested advanced features such as nested constraints, unions, strict additional-property handling, or complex validation rules.
Log failures with the prompt version, model identifier, schema version, parsing error, and a safely handled sample of the response. Do not expose confidential source text in logs by default.
Common mistakes
| Problem | Likely cause | Practical fix |
|---|---|---|
| Extra prose surrounds the JSON | The instruction is weak, or the interface is designed for conversational replies | Use a native structured-output mode where available and state “valid JSON only” in the prompt. Reject non-JSON responses rather than silently accepting them. |
| Required fields are missing | The schema does not define required fields, or the prompt does not explain absent-value behavior | Mark fields as required and specify whether missing information becomes null, an empty array, or a fallback value. |
| Wrong data types | Examples and instructions conflict, or the model treats all values as text | Declare types explicitly, show one correct example, and validate types in application code. |
| Invalid dates or inconsistent labels | The desired format is implied rather than stated | Specify an exact format such as YYYY-MM-DD and enumerate permitted labels. |
| Nested objects are malformed | Cardinality and required child fields are unclear | Show the complete nested shape and test zero, one, and many child objects. |
| Repair prompts create new errors | The repair step receives incomplete context or changes the original task | Send the original schema and the validation error together. Limit repair attempts and route repeated failures for review. |
Avoid relying on regular expressions as a complete JSON validator. Regex can help locate or clean predictable wrappers, but it is not a replacement for a standards-compliant parser and schema validator. The Regex Tester for AI Text Pipelines is useful for testing narrow cleanup rules, not for proving that arbitrary nested JSON is valid.
Also avoid asking the model to “never fail.” Replace that instruction with observable rules: exact keys, allowed values, null behavior, and a defined failure path. For security-sensitive applications, keep untrusted content separate from system instructions and review the Prompt Injection Defense Checklist.
When to revisit
Review structured output prompts whenever the workflow, model, or schema changes. A useful maintenance checklist is:
- Re-run representative examples when changing models, providers, API modes, temperature settings, or token limits.
- Test boundary cases before seasonal planning cycles or large publishing campaigns: empty input, long input, multiple records, missing fields, unusual characters, and conflicting evidence.
- Version the prompt and schema together so a failed response can be traced to the exact contract in use.
- Compare parse-success rates, validation failures, retries, and manual-review volume after a change.
- Update platform-specific instructions when structured-output features, supported schema syntax, or model behavior changes.
- Recheck downstream consumers whenever a field is renamed, retyped, made optional, or given new allowed values.
When migrating providers or models, do not assume equivalent behavior from equivalent prompts. Use the LLM Provider Migration Checklist, run the same test set against both systems, and inspect differences in edge cases rather than comparing only successful examples. For prompts used across an application, the Production System Prompt Design Checklist provides a useful versioning and deployment companion.
The practical rule is simple: define the contract, enforce it with available platform controls, validate every response, and maintain a safe fallback. That combination makes LLM JSON output far more dependable than prompt wording alone.