JSON Schema for LLM: How to Validate Structured Output
When working with LLMs, it's often necessary to receive not just text, but strictly structured data: JSON objects for integration with APIs, databases, or interfaces. Without validation, the system becomes fragile: the model may return an incorrect type, omit a required field, or generate incorrect nesting. In this article, I will explain how to use JSON Schema to validate structured output from LLMs, what errors occur most frequently, and how to handle them.
Why Validate Structured Output
LLMs are probabilistic systems. Even when using the response_format or json_object mode, the model may return data that does not match the expected schema. Reasons:
- The model is not trained on a specific schema and generates fields with different names;
- Nested objects contain extra or missing keys;
- Values have incorrect types (string instead of number);
- The model returns null for required fields.
Validation through JSON Schema allows:
- To filter out incorrect responses before passing them to business logic;
- To automatically generate an error message for a retry request;
- To document the contract between the LLM and the rest of the system.
Defining the Schema
JSON Schema is a standard for describing the structure of a JSON document. For LLM output, I use a minimal set of keywords: type, properties, required, additionalProperties, enum, pattern.
Example schema for extracting product data:
{
"type": "object",
"properties": {
"name": { "type": "string" },
"price": { "type": "number", "minimum": 0 },
"currency": { "type": "string", "enum": ["RUB", "USD", "EUR"] },
"available": { "type": "boolean" },
"tags": { "type": "array", "items": { "type": "string" } }
},
"required": ["name", "price", "currency"],
"additionalProperties": false
}
required — list of required fields;
- additionalProperties: false — prevents the model from adding extra keys;
- enum — limits acceptable values;
- pattern — specifies a regular expression for strings.
Integration with LLM API
Most providers support the response_format parameter. For example, in the OpenAI API:
from openai import OpenAI
customer = OpenAI()
response = customer.chat.completions.create(
model="gpt-4o",
response_format={ "type": "json_object" },
messages=[
{"role": "system", "content": "You are an assistant. Respond only in JSON."},
{"role": "user", "content": "Extract product data: Laptop, 75000 rubles"}
]
)
raw = response.choices[0].message.content
raw string, it needs to be parsed and validated. For validation, I use the jsonschema library in Python:
import json
from jsonschema import validate, ValidationError
schema = { ... } # schema from the example above
try:
data = json.loads(raw)
validate(instance=data, schema=schema)
except json.JSONDecodeError:
print("Response is not valid JSON")
except ValidationError as e:
print(f"Validation error: {e.message}")
Error Handling and Retry Requests
If validation fails, I don't discard the response immediately. Instead, I form a new request to the model, including the error message in it. This increases the likelihood of getting a correct result.
def extract_product(text, schema, max_retries=2):
for attempt in range(max_retries + 1):
response = customer.chat.completions.create(
model="gpt-4o",
response_format={ "type": "json_object" },
messages=[
{"role": "system", "content": "You are an assistant. Respond only in JSON."},
{"role": "user", "content": f"Extract data: {text}"}
] + ([
{"role": "assistant", "content": raw},
{"role": "user", "content": f"Validation error: {error}. Fix the response."}
] if attempt > 0 else [])
)
raw = response.choices[0].message.content
try:
data = json.loads(raw)
validate(instance=data, schema=schema)
return data
except (json.JSONDecodeError, ValidationError) as e:
error = str(e)
raise ValueError("Failed to get valid JSON after several attempts")
Typical Errors and Their Causes
| Error | Cause | Solution |
|---|---|---|
additionalProperties not allowed |
The model added a field not specified in the schema | Remove additionalProperties: false or add the field to the schema |
'price' is a required property |
The model omitted a field | Clarify in the prompt that all fields are required |
'RUB' is not one of ['USD', 'EUR'] |
The model chose a value outside the list | Expand enum or add an instruction in the prompt |
'75000' is not of type 'number' |
The model returned a string instead of a number | Use type: ['number', 'string'] and convert |
| ## Practical Recommendations | ||
| 1. Include the schema in the prompt. The model follows the structure better if it sees its description. You can pass the schema as a JSON string in the system message. | ||
2. Use additionalProperties: false only when you are sure the schema is complete. Otherwise, the model will receive errors at each step. |
||
| 3. Allow strings for numbers. LLMs often return numbers in quotes. It's better to accept a string and convert it than to make a retry request. | ||
| 4. Log validation errors. This helps understand which fields the model generates inconsistently and improve the prompt. | ||
5. Do not rely solely on response_format. It guarantees JSON but does not guarantee compliance with the schema. |
||
| ## Conclusion | ||
| JSON Schema is a reliable way to control structured output from LLMs. Validation does not eliminate errors completely, but it makes the system predictable: incorrect responses are filtered out, and retry requests increase the likelihood of success. By combining the schema with a well-thought-out prompt and error handling, I get stable data for further processing. For more on structured output, see the validation guide, and for basic principles, the glossary. |