Sub topic 2
Describing the shape you want with JSON Schema
This chapter assumes you can read and write JSON, you know basic Python classes and exceptions, and you have called an LLM API at least once. By the end you will be able to write a JSON Schema for the output you want. You will also know which keywords providers usually accept and which mistakes cause trouble in practice.
What JSON Schema is for
A JSON Schema is a JSON document that describes the shape of other JSON documents. It lists the fields an object may have, the type of each field, which fields are required, and which values are allowed.
A schema serves three jobs in a structured-output pipeline:
- Contract. You and the model agree on what a valid reply looks like.
- Instruction. Providers that support schema-constrained output read your schema and restrict what the model can generate. Field names and
descriptiontext also guide the model. - Check. After the reply arrives, a validator compares it with the schema and tells you whether it conforms.
The schema describes shape, not truth. A reply can match the schema and still be wrong. Chapter material on validation and failure modes returns to this point.
A first schema
The running example in this tutorial is a support-ticket triage step. The model reads a ticket and returns a category, a priority, and a one-sentence summary.
{
"type": "object",
"properties": {
"category": {
"type": "string",
"enum": ["billing", "bug", "feature_request", "other"]
},
"priority": {
"type": "integer",
"description": "1 is most urgent, 3 is least urgent"
},
"summary": {
"type": "string",
"description": "One-sentence summary of the ticket"
}
},
"required": ["category", "priority", "summary"],
"additionalProperties": false
}Read it from the top:
"type": "object"says the whole reply is a JSON object, not an array or a bare string.propertiesmaps each allowed field name to a sub-schema that describes that field's value.requiredlists the fields that must be present.additionalProperties: falseforbids any field not listed inproperties.
A reply that this schema accepts:
{"category": "bug", "priority": 1, "summary": "Checkout page returns a 500 error for all users."}Replies that it rejects:
{"category": "bug", "priority": 1}is missingsummary.{"category": "refund", "priority": 1, "summary": "..."}uses a value outside the enum.{"category": "bug", "priority": "high", "summary": "..."}gives a string where an integer is required.{"category": "bug", "priority": 1, "summary": "...", "mood": "angry"}has an extra field.
The core building blocks
Types
The type keyword takes one of seven names.
| Type | Matches | Notes |
|---|---|---|
| `string` | `"hello"` | Any text. |
| `integer` | `3` | Whole numbers only. `3.0` is accepted by some validators and not others. |
| `number` | `3`, `3.5` | Any integer or float. |
| `boolean` | `true`, `false` | Lowercase in JSON. |
| `null` | `null` | Only the null value. |
| `object` | `{"a": 1}` | Fields are described by `properties`. |
| `array` | `[1, 2]` | Items are described by `items`. |
Prefer integer over number when the value is a count, rank, or score. The narrower type removes values like 2.5 that your code would have to handle.
Enums
enum lists the only values a field may take. It is the most useful keyword for classification output, because it turns an open-ended text field into a closed choice.
{
"type": "string",
"enum": ["billing", "bug", "feature_request", "other"]
}Include an escape value such as "other" when real inputs might not fit any listed option. Without one, the model must pick a wrong category.
Required fields and optional fields
A field listed in properties but not in required is optional. The model may omit it, and your code must handle the missing key. In many structured-output designs, it is simpler to make every field required and allow null when a value may be absent.
{
"type": "object",
"properties": {
"order_id": { "type": ["string", "null"] }
},
"required": ["order_id"],
"additionalProperties": false
}Here order_id is always present, and the value is either a string or null. Your code reads data["order_id"] and checks for None. It never has to ask whether the key exists.
Nested objects
A property can itself be an object with its own properties, required, and additionalProperties. Each level needs its own settings. Setting additionalProperties: false at the top does not apply to nested objects.
{
"type": "object",
"properties": {
"customer": {
"type": "object",
"properties": {
"name": { "type": "string" },
"email": { "type": "string" }
},
"required": ["name", "email"],
"additionalProperties": false
}
},
"required": ["customer"],
"additionalProperties": false
}Arrays
An array schema uses items to describe each element. minItems and maxItems limit its length in validators that support them.
{
"type": "object",
"properties": {
"tags": {
"type": "array",
"items": { "type": "string" },
"maxItems": 5
}
},
"required": ["tags"],
"additionalProperties": false
}Arrays of objects work the same way: put an object schema under items.
Descriptions
description is a plain-text note on any schema node. A validator ignores it. A model does not: providers pass your descriptions to the model, so they work as per-field instructions. The priority description in the first schema, "1 is most urgent, 3 is least urgent", fixes a direction that the bare name priority leaves ambiguous.
Limits: what validators check and what providers accept
JSON Schema defines many keywords for limits, including minimum, maximum, minLength, maxLength, pattern, and format. The full specification is large. Two separate programs read your schema, and they do not support the same set.
- A validator library, run in your own code, checks a reply after it arrives. It usually supports most keywords.
- A provider with schema-constrained output reads the schema before generation and builds restrictions from it. It supports a subset, and the subset differs between providers and changes over time.
Common differences:
| Keyword | Typical validator | Typical provider with constrained output |
|---|---|---|
| `type`, `properties`, `required`, `enum` | Supported | Supported |
| `additionalProperties: false` | Supported | Often required |
| `minimum`, `maximum` | Supported | Varies, sometimes rejected or ignored |
| `minLength`, `maxLength`, `pattern` | Supported | Varies |
| `$ref`, `$defs` | Supported | Often supported, with limits on recursion |
| `oneOf`, `anyOf` | Supported | Varies, `anyOf` is more common than `oneOf` |
Check your provider's current documentation before relying on any keyword outside the first row. The table describes typical behavior, not a guarantee.
If a provider ignores a keyword silently, the model can return a value that breaks the limit, and no error appears at generation time. This is why you validate every reply in your own code, whatever the provider promises. The hand-written schema above deliberately leaves out minimum and maximum on priority for portability. The Pydantic version in the next chapter section expresses the same limits, and your validator enforces them after the reply arrives.
Generating a schema from Python
Writing schemas by hand is useful for learning and for small cases. In a Python project you can define the shape once as a Pydantic model and generate the schema from it. This keeps the schema and your code from drifting apart.
from typing import Literal
from pydantic import BaseModel, Field
class TicketTriage(BaseModel):
category: Literal["billing", "bug", "feature_request", "other"]
priority: int = Field(ge=1, le=3, description="1 is most urgent, 3 is least urgent")
summary: str = Field(max_length=200, description="One-sentence summary of the ticket")
print(TicketTriage.model_json_schema())The printed schema contains the same type, enum, and description entries as the hand-written one. It also contains minimum: 1, maximum: 3, and maxLength: 200, which come from the Field limits. It does not include additionalProperties: false by default. Pydantic's default is to ignore extra fields when it validates, so the generated schema stays silent about them. If your provider requires the keyword, set it in the model:
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
class TicketTriage(BaseModel):
model_config = ConfigDict(extra="forbid")
category: Literal["billing", "bug", "feature_request", "other"]
priority: int = Field(ge=1, le=3, description="1 is most urgent, 3 is least urgent")
summary: str = Field(max_length=200, description="One-sentence summary of the ticket")
print(TicketTriage.model_json_schema())With extra="forbid", the generated schema includes "additionalProperties": false, and Pydantic also rejects extra fields during validation. The next chapter covers Pydantic models in more detail.
Checking a reply against a schema
You can validate a reply against a schema directly with the jsonschema package, without Pydantic. Install it with pip install jsonschema.
import json
from jsonschema import Draft202012Validator
schema = {
"type": "object",
"properties": {
"category": {"type": "string", "enum": ["billing", "bug", "feature_request", "other"]},
"priority": {"type": "integer", "minimum": 1, "maximum": 3},
"summary": {"type": "string"},
},
"required": ["category", "priority", "summary"],
"additionalProperties": False,
}
reply = '{"category": "refund", "priority": 5, "summary": "Customer wants money back."}'
data = json.loads(reply)
validator = Draft202012Validator(schema)
for error in validator.iter_errors(data):
print(list(error.path), "->", error.message)This prints one line for each violation, here a bad enum value for category and a number above the maximum for priority. Collecting all errors, rather than stopping at the first, gives you a complete message to feed back to a model later.
Notice the two steps. json.loads checks that the text is valid JSON, and the validator checks that the parsed data fits the schema. A reply can fail at either step, and the two failures have different causes.
Common mistakes
- Missing
additionalProperties: false. Some providers require it for constrained output. Without it, other tools let the model invent extra fields. - Forgetting nested settings. Every nested object needs its own
requiredandadditionalProperties. - Vague names with no description. A field named
scoreleaves the scale unclear. Name iturgency_1_to_3or add a description. - Using free strings for closed choices. If you have a fixed set of values, use
enum. Do not write the options in the description and hope. - Relying on unsupported keywords. A schema that validates in your tests may be partly ignored at the provider. Validate replies in your own code.
- Treating
numberasinteger. Useintegerwhen you mean whole numbers.
Choosing what to put in a schema
A short checklist for a first schema:
- List the fields your code actually reads. Leave out anything it does not use.
- Choose the narrowest type for each field.
- Turn every closed choice into an
enum, with an escape value if inputs may not fit. - Add a
descriptionwherever a field name alone could be read two ways. - Make fields required and use
nullfor "not present." - Set
additionalProperties: falseon every object. - Keep limits you must enforce in your validator, and treat provider support for them as a bonus.
Exercise
A schema has "priority": {"type": "integer", "minimum": 1, "maximum": 3}, and your provider supports schema-constrained output. A reply arrives with "priority": 7. Give two possible reasons this can happen, and say what protects your program in both cases.
Show answer
Possible reasons: the provider ignores minimum and maximum without an error, so generation was not restricted by them; or the reply came from a prompt-only or JSON-mode call, where no schema constrains generation at all. In both cases, validating the parsed reply in your own code (for example with jsonschema or a Pydantic model that has ge=1, le=3) catches the value 7 before the program uses it.
Exercise
Write a JSON Schema for an object with a required string field "title" and a required array field "tags" that holds at most 5 strings. Extra fields must be forbidden.
Show answer
{"type": "object", "properties": {"title": {"type": "string"}, "tags": {"type": "array", "items": {"type": "string"}, "maxItems": 5}}, "required": ["title", "tags"], "additionalProperties": false}