Dev tools
LLM JSON Output: How to Make It Reliable
Get LLM JSON output that never breaks your app: compare prompting, JSON mode, structured outputs and validation, with a simple pattern that works in production.
Getting reliable LLM JSON output is one of the first real problems you hit when you move from chatting with a model to building an app on top of it. Your code needs data it can parse: a list of tags, an extracted invoice, a classification label. But a language model writes text, and text can drift. One response wraps the JSON in a friendly sentence, the next forgets a closing bracket, and the next invents a field your code never expected.
The good news is that this is a solved problem if you use the right tools. This guide explains the four levels of control, from simply asking nicely to structured outputs with constrained decoding, and shows a simple pattern that holds up in production.
Why LLM JSON Output Breaks
A model generates one token at a time, choosing likely next pieces of text. Nothing in that process knows that a JSON object must be closed, or that a field called price must be a number. Usually the model gets it right, because it has seen plenty of JSON. But "usually" isn't good enough when thousands of requests a day feed into your database.
The common failures are:
- Extra text around the JSON, such as "Sure! Here's the data:" or a closing note.
- Code fences, where the JSON is wrapped in a Markdown code block.
- Broken syntax: a trailing comma, a missing bracket or an unescaped quote.
- Wrong shape: missing fields, extra fields, wrong types or a different structure than you asked for.
- Cut-off answers when the output hits the length limit halfway through.
- Valid but wrong values, like a made-up date or a category that doesn't exist.
The first five are format problems, and modern APIs can eliminate them. The last one is a content problem, and you still need your own checks for it.
Level 1: Ask in the Prompt
The simplest approach is to describe the format and give an example:
Extract the product and price from the review below.
Reply with JSON only, no other text, in exactly this format:
{"product": "string", "price": number or null}Clear instructions and an example get you most of the way with capable models. Our prompt engineering guide covers the techniques that help most, such as showing examples and stating rules plainly. But prompting alone is a request, not a guarantee. Expect occasional failures, and never ship it without validation behind it.
Level 2: JSON Mode
Many APIs offer a JSON mode. When it's on, the model is forced to produce syntactically valid JSON: brackets close, strings are quoted, and there's no chatty text around it.
JSON mode fixes broken syntax, but not the shape. The output will parse, yet it may still have the wrong fields or types. You still need to describe the structure in your prompt and check it afterwards. Some providers also require the word "JSON" to appear in your instructions when JSON mode is on.
Level 3: Structured Outputs With a JSON Schema
Structured outputs go one step further. Instead of just asking for valid JSON, you hand the API a JSON Schema, a standard description of the exact fields, types and allowed values. The model's output is then forced to match that schema.
{
"type": "object",
"properties": {
"product": { "type": "string" },
"price": { "type": ["number", "null"] },
"sentiment": { "type": "string", "enum": ["positive", "neutral", "negative"] }
},
"required": ["product", "price", "sentiment"],
"additionalProperties": false
}With a strict schema, the response will always have exactly these three fields, sentiment will always be one of the three allowed words, and price will be a number or null. Most major providers now support this in some form, either directly for responses or through tool definitions with a strict setting. Our guide to function calling shows how tool definitions use the same JSON Schema.
How constrained decoding works
The magic behind structured outputs is constrained decoding. At every step, before the model picks its next token, the system works out which tokens would still keep the output valid for your schema and blocks all the others.
If the schema says the next thing must be the key "price", the model can only produce that. If a field allows only "positive", "neutral" or "negative", every other word is ruled out. The model still decides the content, but it can't step outside the shape.
Schema limits to know
Strict modes usually support only part of JSON Schema. Common rules include marking every field as required (use a nullable type for optional values), setting additionalProperties to false, and avoiding some advanced features. Check your provider's documentation, keep schemas fairly flat, and test them before you rely on them.
Level 4: Validate Everything in Your Code
Even with structured outputs, validate the result in your own code. Validation catches anything the API didn't guarantee, such as a value that's the right type but out of range, and it protects you if you switch to a model or provider with weaker guarantees.
In Python, Pydantic is the usual tool. You define the shape once, and it both produces the JSON Schema and validates the response:
from pydantic import BaseModel, Field, ValidationError
from typing import Annotated, Literal
class Review(BaseModel):
product: str
price: Annotated[float, Field(ge=0)] | None # required, may be null
sentiment: Literal["positive", "neutral", "negative"]
schema = Review.model_json_schema() # send this to the API as the schema
def parse_review(raw: str) -> Review | None:
try:
return Review.model_validate_json(raw)
except ValidationError as err:
print("invalid output:", err)
return NoneIf validation fails, a common fix is one retry: send the model its previous answer together with the validation error and ask it to correct the output. Libraries such as Instructor wrap this retry loop for you. Keep retries limited, one or two at most, and log every failure so you can spot patterns.
Tips for Better Structured Outputs
- Name fields clearly.
invoice_total_euris better thanval2. The model reads field names and descriptions as instructions. - Add descriptions to fields that need explaining, such as the expected date format.
- Use enums for categories, so the model can't invent new ones.
- Allow "unknown." Give the model a null value or an "unknown" option, so it doesn't make something up when the input doesn't contain the answer.
- Keep it small. Ask for the fields you need. Long, deeply nested schemas cause more errors and cost more tokens.
- Leave room. Set the maximum output length high enough that the JSON never gets cut off.
- Order fields thoughtfully. If you want the model to reason before answering, put a short
reasoningfield before theanswerfield, because the model writes them in order.
LLM JSON Output With Local Models
If you run models yourself, you can get the same guarantees. Inference engines like llama.cpp support grammars that restrict output, and serving tools such as vLLM and SGLang offer schema-guided generation through libraries like XGrammar and Outlines. Small local models benefit most, because they slip on formatting more often than large hosted models.
Which Method Should You Use?
| Method | Valid JSON | Correct shape | Effort |
|---|---|---|---|
| Prompt only | Usually | Usually | Lowest |
| JSON mode | Yes | Not guaranteed | Low |
| Structured outputs | Yes | Yes | Medium |
| Plus your own validation | Yes | Yes, with value checks | Medium |
For anything in production, use structured outputs with a schema wherever your provider supports it, and validate in your code every time. Use prompting and JSON mode only as a fallback for models that don't support schemas.
FAQ
How do I force an LLM to output JSON?
Use your provider's structured outputs feature with a JSON Schema, which constrains the model so its output always matches the schema. If that isn't available, use JSON mode plus a clear prompt with an example, and validate the result in your code.
What is the difference between JSON mode and structured outputs?
JSON mode guarantees valid JSON syntax but not a particular structure. Structured outputs take a JSON Schema and guarantee that the response matches it: the right fields, types and allowed values.
Does structured output reduce quality?
Usually not in a noticeable way for normal extraction and classification tasks, and it removes formatting failures entirely. Very complex or unusual schemas can make answers worse, so keep schemas simple and test them on real examples.
What is constrained decoding?
It is a technique that limits which tokens a model may choose at each step, so the output always follows a set format such as a JSON Schema. Tokens that would break the format are blocked before the model can pick them.
Do I still need validation with structured outputs?
Yes. Structured outputs guarantee the shape, not that the values are correct. Validation catches values that are out of range or don't make sense, and it protects your app if you change models or providers.