Sub topic 2
Describing the shape you want with JSON Schema
This chapter assumes you can read JSON, write basic Python classes, and have called an LLM API at least once. It covers JSON Schema, the format that providers and validators use to describe the output you want.
Why you need a schema
A prompt that says "return the category, priority and summary" leaves room for interpretation. The model might return "Priority": "high" in one reply and "priority": 1 in the next. A schema removes that room. It is a machine-readable description of the allowed shape: which keys exist, what type each value has, and which values are permitted.
JSON Schema is a standard for this. It is itself written in JSON. The same document can serve three jobs:
- It tells the model what to produce, when a provider accepts a schema.
- It lets a validator check a reply before your code uses it.
- It documents the contract between the model step and the rest of your program.
A worked schema
Here is a schema for a support ticket triage result.
{
"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 down.
"type": "object"says the whole reply is a JSON object, not a list or a bare string.propertieslists each key and describes its value.enumrestricts a value to a fixed list.categorycan only be one of four strings.descriptionis free text. Models read it, so it works like a short instruction attached to the field.requiredlists the keys that must be present.additionalProperties: falseforbids any key not listed inproperties.
The building blocks
| Keyword | What it does | Example |
|---|---|---|
| `type` | Sets the JSON type: `string`, `integer`, `number`, `boolean`, `array`, `object`, `null` | `"type": "integer"` |
| `enum` | Allows only the listed values | `"enum": ["bug", "other"]` |
| `required` | Names keys that must appear | `"required": ["category"]` |
| `additionalProperties` | Controls whether unlisted keys are allowed | `false` rejects extras |
| `items` | Describes each element of an array | `"items": {"type": "string"}` |
| `description` | Explains a field in plain language | `"description": "Order ID"` |
Arrays and nested objects combine these pieces. This schema describes a list of tags:
{
"type": "object",
"properties": {
"tags": {
"type": "array",
"items": { "type": "string" }
}
},
"required": ["tags"],
"additionalProperties": false
}Checking a reply against a schema
You can validate a reply with the jsonschema package (pip install jsonschema). This script runs as shown.
import json
from jsonschema import ValidationError, validate
schema = {
"type": "object",
"properties": {
"category": {"type": "string", "enum": ["billing", "bug", "feature_request", "other"]},
"priority": {"type": "integer"},
"summary": {"type": "string"},
},
"required": ["category", "priority", "summary"],
"additionalProperties": False,
}
good = '{"category": "bug", "priority": 1, "summary": "App crashes on login."}'
bad = '{"category": "urgent", "priority": "high", "summary": "App crashes."}'
for raw in (good, bad):
try:
validate(instance=json.loads(raw), schema=schema)
print("valid")
except ValidationError as err:
print("invalid:", err.message)The first reply passes. The second fails because "urgent" is not in the enum. Note that json.loads only proves the text is valid JSON. The schema check proves it has the right shape.
Common errors
- Forgetting
required. Properties are optional by default. A reply with noprioritykey still passes unlesspriorityis listed inrequired. - Leaving
additionalPropertiesopen. Withoutfalse, a model can add keys such as"notes"and the reply still validates. - Expecting limits to be enforced everywhere. Keywords like
minimumandmaxLengthare valid JSON Schema, but providers that accept schemas for constrained output often support only a subset. The hand-written schema above omits the 1 to 3 range for that reason. Check your provider's documentation, and validate limits in your own code. - Vague descriptions.
"description": "the priority"tells the model little. State the scale and what each end means.
Exercise
A model returns {"category": "bug", "priority": 2, "summary": "Crash", "notes": "seen twice"}. The triage schema above has additionalProperties set to false. Does this reply validate? What changes if you remove that line?
Show answer
It does not validate, because notes is a key that properties does not list. If you remove additionalProperties: false, extra keys are allowed by default, so the reply validates.
Exercise
Write a schema fragment for a field named sentiment that must be one of positive, neutral, or negative, and explain why enum is better than only describing the options in the prompt.
Show answer
"sentiment": {"type": "string", "enum": ["positive", "neutral", "negative"]}. With enum, a validator rejects any other value, such as "Positive" or "mixed", and schema-constrained decoding can prevent the model from producing one. A prompt instruction can be ignored without any error.