JSON Schema in Prompts
Constraining output shape.
JSON Schema in Prompts is a free AI Prompt Engineering lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Prompt Engineering learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Schema as the Output Contract
A JSON Schema declaratively describes the shape of valid output: types, required keys, value constraints, and nesting. When passed to a structured-output API it becomes a hard contract; when embedded in a prompt it becomes strong guidance.
Mastering schema authoring is the core skill of structured generation.
The strict Flag Changes Everything
In strict mode, providers require that every property is listed in required and that additionalProperties is false. Optional fields are expressed as a union with null, not by omission.
{
'type': 'object',
'properties': {
'name': {'type': 'string'},
'nickname': {'type': ['string', 'null']}
},
'required': ['name', 'nickname'],
'additionalProperties': False
}Constraining Scalar Values
Push validation into the schema instead of post-processing:
enumfor fixed choices.minimum/maximumfor numeric ranges.patternfor regex-validated strings.formathints likedate-timeoremail.
{
'rating': {'type': 'integer', 'minimum': 1, 'maximum': 5},
'sku': {'type': 'string', 'pattern': '^[A-Z]{3}-[0-9]{4}$'},
'created': {'type': 'string', 'format': 'date-time'}
}Arrays and Tuples
Use items for homogeneous arrays and add minItems/maxItems to bound length. For positional tuples, supply an array of schemas via prefixItems.
{
'tags': {
'type': 'array',
'items': {'type': 'string'},
'minItems': 1,
'maxItems': 5
}
}Discriminated Unions with oneOf
Model polymorphic results with oneOf plus a discriminator field. The model picks exactly one branch, and your deserializer switches on the tag.
{
'oneOf': [
{'type': 'object', 'properties': {
'kind': {'const': 'email'},
'address': {'type': 'string', 'format': 'email'}},
'required': ['kind', 'address']},
{'type': 'object', 'properties': {
'kind': {'const': 'phone'},
'number': {'type': 'string'}},
'required': ['kind', 'number']}
]
}Generate Schemas from Types
Hand-writing schemas is error-prone. Derive them from typed models so the schema and your code never drift apart.
from pydantic import BaseModel
class Invoice(BaseModel):
total: float
currency: str
paid: bool
schema = Invoice.model_json_schema()
# pass schema directly to response_formatDescriptions Are Prompts Too
Every description in the schema is read by the model. Use them to steer semantics, not just document fields.
For example, a description like 'ISO-3166 alpha-2 country code, uppercase' meaningfully improves field accuracy. Treat descriptions as micro-prompts embedded in the contract.
{
'country': {
'type': 'string',
'description': 'ISO-3166 alpha-2 code, uppercase, e.g. US, TR, DE'
}
}Embedding Schema in the Prompt
When the provider lacks native support, embed the schema in the prompt and demand conformance. Pair it with a single in-context example and an explicit JSON-only, no prose instruction.
SYSTEM = (
'You output ONLY JSON matching this schema. No markdown, no commentary.\n'
'Schema:\n' + json.dumps(schema) + '\n'
'If a value is unknown, use null.'
)Avoiding Schema Bloat
Overly deep or branchy schemas confuse the model and inflate token cost. Guidelines:
- Keep nesting shallow; flatten where possible.
- Prefer enums over free strings.
- Split a giant schema into multiple focused calls.
- Some providers cap nesting depth and total properties; check limits.
Refs and Reuse
Use $defs and $ref to reuse sub-schemas (e.g., an Address used in billing and shipping). Note that some strict modes restrict recursion depth, so verify support before relying on self-referential refs.
{
'$defs': {
'Address': {'type': 'object', 'properties': {
'city': {'type': 'string'}}, 'required': ['city'],
'additionalProperties': False}
},
'type': 'object',
'properties': {
'billing': {'$ref': '#/$defs/Address'},
'shipping': {'$ref': '#/$defs/Address'}
},
'required': ['billing', 'shipping'],
'additionalProperties': False
}Validate the Schema Itself
A subtle bug class: the schema is malformed, not the output. Lint and validate schemas in CI against the JSON Schema meta-schema, and round-trip a sample object through your validator before shipping.
import jsonschema
jsonschema.Draft202012Validator.check_schema(schema)
# also: validate a known-good sample
jsonschema.validate(sample_obj, schema)Quick Check
In a provider's strict JSON Schema mode, how is an optional field correctly expressed?
Recap
You can now author precise schemas:
- strict mode demands all-required plus additionalProperties false.
- Constrain scalars with enum, range, pattern, format.
- Model polymorphism with oneOf discriminators.
- Generate schemas from typed models; treat descriptions as micro-prompts.
- Validate the schema itself in CI.
Next: applying schemas to tool and function calling.
Frequently asked questions
Is the “JSON Schema in Prompts” lesson free?
Yes — the full text of “JSON Schema in Prompts” is free to read here on the web, and the AI Prompt Engineering course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Prompt Engineering course, upgrade to CoddyKit PRO.
What will I learn in “JSON Schema in Prompts”?
Constraining output shape. You practise AI Prompt Engineering with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Prompt Engineering?
No prior experience is required. AI Prompt Engineering on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “JSON Schema in Prompts” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Prompt Engineering lesson?
Yes. Every AI Prompt Engineering lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Why Structured Output
- JSON Schema in Prompts
- Tool/Function Schemas
- Repair and Validation Loops