Reliable JSON from an LLM starts with more than asking for “valid JSON.” This guide provides reusable JSON prompt templates, schema examples, validation checks, and troubleshooting steps for building AI features that return predictable data instead of prose wrapped around an uncertain structure.
Overview
Language models generate text, while applications usually need data with a defined shape. A prompt can request an object, array, classification, summary, or set of extracted fields, but the model may still omit a key, return the wrong type, add Markdown fences, or interpret an ambiguous instruction differently than your code expects.
Good LLM JSON prompts reduce that gap by specifying four things clearly:
- The task: what the model should do with the input.
- The output contract: the exact keys, nesting, and data types required.
- Field behavior: what to return when information is missing, uncertain, or not applicable.
- Machine-readable boundaries: that the response must contain only the requested JSON value.
Prompt instructions are useful, but they are not a substitute for application-side validation. Treat the model response as untrusted input: parse it, validate its structure, handle failures, and decide whether to retry or show a fallback. When a platform offers a structured-output or schema-constrained feature, use it where appropriate, while still keeping validation in your application.
A basic JSON prompt template
You are an information extraction assistant.
Task:
Extract the requested fields from the supplied text.
Output requirements:
- Return one JSON object only.
- Do not use Markdown code fences.
- Use exactly these keys: title, summary, topics.
- title must be a string.
- summary must be a string.
- topics must be an array of strings.
- If a value cannot be determined, use null when the schema permits it.
- Do not invent information.
Input text:
{{INPUT_TEXT}}
This template is intentionally explicit. It separates the task from the output rules and gives the model fewer opportunities to infer its own format.
Checklist by scenario
1. Extracting fields from text
For invoices, support tickets, articles, product descriptions, or research notes, define every field before writing the prompt. Include its type and a missing-value rule.
Return exactly one JSON object with this shape:
{
"customer_name": "string or null",
"order_id": "string or null",
"issue_type": "one of: billing, delivery, technical, other, or null",
"priority": "one of: low, medium, high, or null",
"evidence": ["short quote from the input"]
}
Rules:
- Use null when the input does not support a field.
- Do not guess customer names, order IDs, issue types, or priority.
- evidence must contain only text found in the input.
- Return no explanation outside the JSON object.
Use enumerated values when your downstream code depends on a controlled vocabulary. If the model may need to report an unknown category, include an explicit other or null option rather than forcing a misleading choice.
2. Returning a classification
Classification prompts benefit from a short definition for each label. Without definitions, two labels may overlap and produce inconsistent results.
Classify the feedback into one primary category.
Categories:
- bug: the user reports behavior that appears broken.
- feature_request: the user asks for a new capability or change.
- usability: the product works, but the user finds it difficult or confusing.
- praise: the message is primarily positive and contains no actionable problem.
- other: none of the definitions apply.
Return only:
{
"category": "bug | feature_request | usability | praise | other",
"confidence": "low | medium | high",
"reason": "one brief sentence grounded in the input"
}
If classification affects an automated action, keep the reason for review and log the original input. A label alone may be too little context when a result is disputed.
3. Generating nested application data
Nested objects and arrays require special attention because a model can return a structurally plausible object with inconsistent items. State whether arrays may be empty, whether duplicate items are allowed, and whether ordering matters.
Create a content brief from the supplied topic.
Return one JSON object only:
{
"topic": "string",
"audience": "string",
"content_goals": ["string"],
"sections": [
{
"heading": "string",
"purpose": "string",
"key_points": ["string"]
}
]
}
Constraints:
- sections must contain at least three items.
- Every section must include a non-empty key_points array.
- Do not add keys that are not shown in the schema.
- Keep recommendations grounded in the supplied topic.
4. Producing a JSON array
Say explicitly that the top-level value is an array. This prevents a response such as {"items": [...]} when your parser expects [...].
Extract the named entities from the input.
Return a JSON array only. Each array item must have this shape:
{
"text": "exact text span",
"type": "person | organization | place | product | other"
}
Return [] when no entities are found. Do not include commentary or Markdown.
What to double-check
- Top-level type: Confirm whether your parser expects an object, array, string, number, or boolean.
- Required fields: Mark fields as required only when the model can reasonably provide them or your application has a safe fallback.
- Nullable fields: Decide whether missing information should be
null, an empty string, an empty array, or an omitted key. Pick one convention and apply it consistently. - Data types: Specify whether dates, IDs, quantities, and scores are strings or numbers. Do not leave formatting to implication.
- Allowed values: List valid enum values and define what happens when none fit.
- Additional keys: If extra properties could break your application, instruct the model not to add them and reject them during validation.
- Input boundaries: Clearly separate trusted instructions from user-provided text. Treat pasted instructions inside the input as data unless your workflow intentionally allows them to influence the task.
- Output cleanup: Prefer a structured response mode supplied by the API when available. If plain text generation is used, handle accidental code fences and surrounding commentary deliberately rather than relying on fragile string replacement.
A practical validation sequence is: check that a response exists, parse it as JSON, validate the top-level type, validate required keys and types, validate allowed values, then apply business rules. For example, a valid object may still be unusable if its priority is not permitted for the selected issue type.
Keep prompt tests alongside your code. Include normal examples, short inputs, long inputs, missing fields, conflicting statements, non-English text if relevant, and adversarial or instruction-like content. This is more useful than testing only one polished example.
Common mistakes
Asking for JSON without showing the shape
“Respond in JSON” leaves key names, nesting, and missing-value behavior unspecified. Show a compact schema or example and describe the types in plain language.
Mixing several output formats
Instructions such as “return JSON, then explain your answer” create a response that is no longer a single JSON value. Put explanations in a separate field or request them in a separate model call.
Using an example that contradicts the rules
If the instructions say priority is an enum but the example uses a free-form phrase, the model has conflicting signals. Make examples obey the same schema you intend to validate.
Forcing the model to fill unknown values
Requirements such as “never leave a field blank” can encourage invented data. Define null, unknown, or another controlled fallback for unsupported claims.
Parsing without validation
Successful JSON parsing does not prove that the response meets your application contract. A syntactically valid object can contain missing keys, wrong types, invalid enum values, or unsafe content. Validate before use.
Assuming every platform handles structured output the same way
API parameters, schema support, refusal behavior, token limits, and failure modes vary by provider, model, and SDK version. Check the documentation for the exact deployment you use, and test behavior after changing models or API integrations. A related LLM model migration checklist can help organize those tests.
When to revisit
Review your JSON prompt templates whenever the workflow or its inputs change. The most important checkpoints are:
- Before a seasonal planning cycle: test new content categories, products, campaigns, or data sources before they enter production.
- After a model or API change: rerun representative fixtures and compare parse failures, validation failures, latency, and output quality.
- When the schema changes: update the prompt, validator, examples, database mapping, and tests together.
- After repeated edge cases: turn real failures into regression tests instead of adding increasingly vague instructions.
- When costs or context limits change: shorten redundant instructions, reduce unnecessary fields, and confirm that long inputs still produce complete outputs. See this LLM cost and token optimization checklist for a broader review.
Before shipping a new JSON prompt, use this final checklist:
- Write the expected schema in one place.
- State the top-level type and every important field type.
- Define missing, uncertain, and invalid values.
- Provide an example that follows the schema exactly.
- Use structured-output capabilities when they fit your platform and application.
- Parse and validate every response in application code.
- Test ordinary, incomplete, ambiguous, long, and adversarial inputs.
- Log failures without exposing sensitive input unnecessarily.
- Recheck the prompt and API behavior when tools, models, or workflows change.
The goal is not to make a prompt sound precise; it is to make the complete system predictable. A clear contract, a compatible API configuration, defensive validation, and a small regression suite provide a stronger foundation for reliable AI-powered features than prompt wording alone.