To get reliable JSON from an LLM, use your provider's structured output feature with a strict JSON schema instead of asking for JSON in the prompt. Then handle what the schema can't cover: refusals, responses cut off at the token limit and values that are well-formed but wrong. Structured output guarantees the shape of the response. Your code still decides whether the content is usable.
Why LLM JSON output breaks in production
Prompt-only JSON works in a demo and fails at volume. Over thousands of requests, a model asked to "return JSON" will eventually wrap it in a sentence, drop a field, rename a key or stop halfway through an array. Each failure looks like a parser bug, but the cause is that nothing constrained the output.
Schema-constrained output removes the formatting failures. Others remain:
- A field filled with a plausible value because the schema had no way to say "not present".
- A refusal or truncated response that doesn't match the schema.
- An enum value returned with different capitalization than the schema lists.
- Valid JSON with a total that doesn't add up or an ID from another customer's account.
JSON mode vs structured output vs tool calling
| Approach | What it guarantees | Use it when |
|---|---|---|
| JSON in the prompt | Nothing | Prototypes only |
| JSON mode | Valid JSON, any shape | The model or API doesn't support schemas |
| Structured output with a strict schema | Valid JSON matching your schema, except refusals and truncation | The response is data your code consumes |
| Strict tool calling | Tool name and arguments match the tool's schema | The model chooses an action and its arguments |
OpenAI's structured outputs guide states the difference plainly: both modes produce valid JSON, but only structured outputs ensure schema adherence. It also notes that JSON mode needs an explicit instruction to produce JSON, and the API rejects the request if the string "JSON" doesn't appear in the context.
How to design a schema for LLM structured output
A schema is part of the prompt. Field names, descriptions and allowed values steer what the model writes.
- Give every field a way to say "unknown". OpenAI's guide warns that the model always tries to follow the schema, which can produce hallucinations when the input doesn't fit. Make fields nullable or add a
not_foundvalue, and say in the prompt when to use it. - Use enums for fixed choices. A
categorywith a fixed list of values is easier to validate and route than free text. Avoid values that differ only in case. - Keep it flat. Deep nesting and many optional or union-typed fields make schemas harder to review and validate, and Anthropic counts them toward its compilation limits.
- Describe ambiguous fields. "Invoice date as printed, not the due date" prevents a whole class of mix-ups.
- Keep explanation fields short. Anthropic's structured outputs documentation notes that a property asking for step-by-step reasoning might lead to a refusal, and suggests asking for a short explanation instead.
- Generate the JSON schema from your types. Define it once in Zod or Pydantic and let the SDK produce the JSON schema, so the two can't drift apart.
A hypothetical schema for extracting fields from a support email:
const TicketFields = z.object({
category: z.enum(["billing", "bug", "account", "other"]),
orderId: z.string().nullable().describe("Order ID exactly as written, or null if none"),
refundRequested: z.boolean(),
summary: z.string().describe("One sentence, no customer names"),
});Provider schema limits to check first
Structured output supports a subset of JSON Schema, and the subset differs by provider. A schema that works with one vendor can return a 400 error with another.
- OpenAI's strict mode requires every field to be listed as required and suggests emulating optional fields with a union that includes
null. Anthropic allows optional fields but counts them toward a per-request limit. - Anthropic lists numeric and string constraints such as
minimumandmaxLengthas unsupported. Its SDK helpers move them into the field description and check them on the response. - Anthropic's limits across all strict schemas in one request include 24 optional parameters and 16 parameters with union types. OpenAI allows up to 5,000 object properties and 10 levels of nesting.
- OpenAI returns keys in schema order. Anthropic places required properties first, then optional ones.
- Anthropic compiles each new schema into a grammar and caches it for 24 hours, so the first request with a new schema is slower. Changing the output format also invalidates the prompt cache.
Recheck these when you switch models. Our post on switching LLM models without breaking production covers rerunning tests when settings like these change.
Handle refusals, truncation and invalid output
Both vendors document cases where a structured response won't match the schema. A safety refusal can take precedence over the schema, and a response that hits the output token limit can be incomplete. Anthropic signals these with stop_reason values of refusal and max_tokens. OpenAI's Responses API returns a refusal content part, or a status of incomplete with max_output_tokens as the reason.
Check the stop condition before you parse, and give each outcome its own path:
// example: check the stop condition before trusting the JSON
if (res.stopReason === "refusal") return { status: "refused" };
if (res.stopReason === "max_tokens") return { status: "truncated" };
const parsed = TicketFields.safeParse(safeJsonParse(res.text));
if (!parsed.success) return { status: "invalid", issues: parsed.error.issues };
const problems = checkBusinessRules(parsed.data, session);
return problems.length ? { status: "review", problems } : { status: "ok", data: parsed.data };Truncation usually means the output limit is too low. Retry once with a higher limit, then send the item to review. A refusal on ordinary business input is worth reading, because it often points at a prompt or field the model reads as a safety issue.
Compare enum values case-insensitively. Anthropic's documentation says structured outputs don't guarantee enum capitalization, and the response completes with no error when it differs.
Validate the values before you act on them
A schema can't express most business rules. Put these checks in code, after parsing:
- Cross-field rules, such as line items summing to the total.
- Lookups against your own data, scoped by the session's identity rather than an ID the model supplied.
- Range and format checks the provider's schema subset can't enforce.
- Allowlists for anything that leads to an action, such as which fields an update may change.
The OWASP entry on improper output handling recommends treating the model as any other user and validating its responses before they reach backend functions. Structured output makes that validation easier to write, and you still have to write it. Our guide to LLM output handling covers output that reaches a browser, a database or a shell.
Retries without loops
Retry only failures a second attempt can fix: a truncated response, a transient API error, or an invalid response from a model without strict schema support.
Don't feed a business rule failure back and ask the model to fix the numbers. It will often produce a response that passes the check without being correct. Send those cases to a person with the reason attached.
Cap retries at one or two, and log each attempt with the prompt version, model ID and outcome. A rising retry rate is often the first visible sign of a bad model or prompt change.
Common mistakes with LLM structured output
- Asking for JSON in the prompt and parsing it with a regex.
- Using JSON mode and assuming it enforces a schema.
- Making every field required with no null option, so the model invents values.
- Parsing before checking for a refusal or truncation.
- Passing schema-valid IDs straight to a database query.
- Tracking parse errors only, and missing valid responses that are wrong.
Track the rate of each outcome per prompt and model version: refused, truncated, invalid and sent to review. Our guide to evaluating LLM output quality in production explains how to add these to your monitoring.
Frequently asked questions
Does structured output make LLM answers less accurate?
It can change behavior, so measure it on your own evaluation set. Compare constrained and unconstrained runs on the same inputs, checking accuracy and refusal rate. Field order and descriptions affect results too, so test schema changes the way you test prompt changes.
Can I stream structured output to the UI?
Yes, both vendors cited here support streaming structured responses. Treat partial JSON as a preview. Validate and act on it only after it completes, because a stream can still end in a refusal or an incomplete response.
Should I use tool calling or a response schema for extraction?
Use a response schema when you always want the same data back. Use tool calling when the model has to choose between actions. If you use tools for extraction anyway, enable strict mode so arguments are checked against the schema.
If you're building an LLM feature that feeds structured data into your systems, our LLM apps, agents and RAG service sets up the evaluation and guardrails that catch bad output before it reaches production.