Chapter 2 · Chains and Structured Output
JSON and Schemas: Fields, Types, Enums and Missing Values
- Page 7 of 24
- 17 min read
People read free text. Programs do not: a billing system, a calendar or the next stage of a chain needs fields it can find, with types it can trust. Getting a model to return those fields reliably is one of the most useful skills in practical prompting, and one of the easiest to get wrong, because a reply that looks like JSON is not yet data your program can use.
This page shows how to specify a JSON output precisely, how to design for missing values, and how far a prompt alone can take you. It continues Chain Reliability: Error Rates, Early Failures, Revision Loops and Fallbacks. You need Python 3.12 or newer, promptlab.py and pip install jsonschema. Type the blocks in order (they share names). The "models" are toy providers: deterministic stand-ins with typical drifts built in, so the checks can be tested repeatably. Real models are less predictable, which is why you test; a toy result says nothing about a real model.
What you will learn
- When to ask for structured output, and how to specify a JSON object: exact field names, required and optional fields, types, enumerations, missing values, nested objects and arrays.
- How to ask for JSON without Markdown wrappers, and what a prompt-only request cannot guarantee.
- The difference between prompted JSON and schema-constrained generation, stated precisely.
Free-form text or structured output
Use free-form text when a person reads the result and wording matters: a summary, an email draft. Use structured output when code reads it: a record to store, a value to branch on, input for the next stage. The same facts can come back both ways. Our running example is a meeting-room request.
Example reply (illustrative; yours will differ):
Aiko Tan would like the Sakura room on 3 November for about 45 minutes, with two
colleagues. She needs a projector. Her email is [email protected].Fine for a person. A program would have to guess where the room, the date and the duration are. Compare:
Example reply (illustrative; yours will differ):
{"requester_name": "Aiko Tan", "requester_email": "[email protected]", "room": "Sakura",
"date": "2026-11-03", "duration_minutes": 45, "needs_projector": true,
"attendees": [{"name": "Ben Ito", "email": null}, {"name": "Mei Sato", "email": null}]}Now every fact has a name and a type. To get it, the prompt must be a specification, not a wish.
Specify the object: names, required fields, types and enumerations
Weak prompt:
Give me the booking details as JSON.This leaves the field names, the date format, the handling of missing data and the surrounding text to chance. A reply may use room today and meeting_room tomorrow.
Better prompt:
Extract the meeting request below as ONE JSON object and nothing else.
No Markdown, no code fence, no text before or after the JSON.
Fields (use exactly these names, no others):
- requester_name: string
- requester_email: string, or null if not given
- room: one of "Sakura", "Maple", "Cedar", "unknown"
- date: "YYYY-MM-DD", or null if the request gives no exact date
- duration_minutes: integer, or null if not given
- needs_projector: true or false (false if not mentioned)
- attendees: array of {"name": string, "email": string or null}; [] if none
- notes: string, optional; leave the field out if there is nothing to add
Never guess a missing value: use null (or "unknown" for room).
### REQUEST
{request}| Specification element | In the prompt above | Why |
|---|---|---|
| Exact field names | "use exactly these names, no others" | Code looks fields up by name; a renamed or extra field breaks it. |
| Required and optional | all fields listed except notes, which may be left out | Required means "always present", possibly as null; optional means "may be absent". |
| Types and formats | string, integer, boolean, array, YYYY-MM-DD | Numbers as numbers, dates in one format. |
| Enumeration | room is one of four values | A closed list can be compared; free labels cannot. Include an explicit escape such as "unknown" or "other". |
| Missing values | "use null", never guess | See below. |
| Nested data | attendees: array of small objects | One level of nesting is usually enough; deep nesting multiplies mistakes. |
Required and optional fields
A required field must always be present, even when its value is unknown (then it is null). An optional field may be absent. Keep the optional list short: every optional field is a place where "absent" is ambiguous. Here only notes is optional, because "nothing to add" is a real, different case.
Types, allowed values and enumerations
Name a type for every field and a format for strings that have one (dates as YYYY-MM-DD, not "3 Nov"). Use an enumeration for any fixed category (a status, a room, a currency code): the model must pick from your list, and code can compare values without fuzzy matching. Spell each value exactly as it must appear, including capital letters, and give one value for "none of these" so the model is not forced into a wrong choice.
Nested objects and arrays
When one request has several people or items, use an array of objects and name the keys of every item (attendees above). Say what an empty list looks like ([], not null) and which item fields can be null. Keep the nesting to one or two levels; each extra level is another place for a missing key or a wrong type.
Write the same specification a second time as a machine-readable JSON Schema, and let code check the reply against it. The schema below is the prompt's contract in code: types, an enumeration, a date pattern, a minimum, an array of nested objects, an optional notes and additionalProperties: False so invented fields are rejected. The problems helper returns short messages; the second call has four deliberate mistakes.
import json, re
from jsonschema import Draft202012Validator
ROOMS = ["Sakura", "Maple", "Cedar"]
SCHEMA = {
"type": "object",
"properties": {
"requester_name": {"type": "string", "minLength": 1},
"requester_email": {"type": ["string", "null"]},
"room": {"enum": ROOMS + ["unknown"]}, # fixed categories, with an explicit escape
"date": {"type": ["string", "null"], "pattern": r"^\d{4}-\d{2}-\d{2}$"}, # null when the request gives no date
"duration_minutes": {"type": ["integer", "null"], "minimum": 1},
"needs_projector": {"type": "boolean"},
"attendees": {"type": "array", "items": { # array of nested objects
"type": "object",
"properties": {"name": {"type": "string"}, "email": {"type": ["string", "null"]}},
"required": ["name", "email"], "additionalProperties": False}},
"notes": {"type": "string"}, # optional: not in "required"
},
"required": ["requester_name", "requester_email", "room", "date", "duration_minutes", "needs_projector", "attendees"],
"additionalProperties": False, # no invented fields
}
Draft202012Validator.check_schema(SCHEMA) # the schema itself is valid
def problems(doc):
"""Short, sorted schema problems (sorted so the output is stable)."""
out = []
for e in Draft202012Validator(SCHEMA).iter_errors(doc):
msg = e.message if e.validator in ("required", "additionalProperties") else f"{e.instance!r} fails {e.validator}"
out.append(f"{'/'.join(map(str, e.path)) or '(top)'}: {msg}")
return sorted(out)
good = {"requester_name": "Aiko Tan", "requester_email": "[email protected]", "room": "Sakura", "date": "2026-11-03",
"duration_minutes": 45, "needs_projector": True, "attendees": [{"name": "Ben Ito", "email": None}]}
print(problems(good))
print(problems({**good, "room": "sakura", "duration_minutes": "45", "colour": "red", "attendees": [{"name": "Ben Ito"}]}))[]
["(top): Additional properties are not allowed ('colour' was unexpected)", "attendees/0: 'email' is a required property", "duration_minutes: '45' fails type", "room: 'sakura' fails enum"]Represent missing values explicitly
When a request does not give a date, a model that must fill the field will often invent one. Say what to put instead and make the schema accept exactly that. Compare four ways to say "unknown":
for label, patch in [("date null", {"date": None}), ("date empty string", {"date": ""}), ("date 'N/A'", {"date": "N/A"}),
("duration null", {"duration_minutes": None}), ("duration 0", {"duration_minutes": 0}),
("room unknown", {"room": "unknown"}), ("email missing key", {"requester_email": ...})]:
doc = {k: v for k, v in {**good, **patch}.items() if v is not ...}
print(f"{label:18}", problems(doc) or "valid")date null valid
date empty string ["date: '' fails pattern"]
date 'N/A' ["date: 'N/A' fails pattern"]
duration null valid
duration 0 ['duration_minutes: 0 fails minimum']
room unknown valid
email missing key ["(top): 'requester_email' is a required property"]Only null (and the "unknown" room) pass. An empty string, "N/A" or 0 look like values and would flow into the next stage unnoticed, so the pattern and the minimum reject them. Making a field required but nullable is better than making it optional: a missing key could mean "not in the request" or "the model forgot", while null is a clear answer. The design question for each field is: what does the program do with "unknown"?
Valid JSON without Markdown wrappers
Ask for the JSON only: "one JSON object and nothing else, no Markdown, no code fence, no text before or after". Programs parse the whole reply, so a friendly sentence or a ```json fence makes parsing fail. Write the instruction as a positive statement of what the reply is, then validate anyway, because the request is a request.
The limits of prompt-only JSON instructions
The next block runs a toy provider on 12 invented requests. It is built to show the typical drifts: a code fence, text before the JSON, a trailing comma, a number returned as a string, an enum value with extra words, an extra field, a missing field and a cut-off reply. The mix of drifts is invented; real rates depend on the model and the prompt, so measure your own.
from promptlab import Client, render
PEOPLE = [("Aiko Tan", "[email protected]", "Sakura", "2026-11-03", 45, ["Ben Ito", "Mei Sato"], True),
("Kwame Mensah", "[email protected]", "Maple", "2026-11-04", 60, [], False),
("Lena Fischer", "[email protected]", "Cedar", None, 30, ["Omar Haddad"], False),
("Priya Nair", "[email protected]", "Sakura", "2026-11-05", 120, ["Nadia Rahman"], True)] * 3
MODES = ["clean", "fence", "clean", "prose", "comma", "clean", "string_number", "bad_enum", "clean", "extra_key", "missing_key", "truncated"]
def request_text(k, p):
name, mail, room, date, mins, others, proj = p
when = f"on {date}" if date else "sometime next week"
dur = f"{mins // 60} hours" if mins % 60 == 0 and mins >= 120 else f"{mins} minutes"
who = f" {' and '.join(others)} will join." if others else ""
return f"#{k}: Hi, this is {name} ({mail}). Please book {room} {when} for {dur}.{who}" + (" We need a projector." if proj else "")
REQUESTS = [request_text(k, p) for k, p in enumerate(PEOPLE)]
GOLD = [{"requester_name": n, "requester_email": m, "room": r, "date": d, "duration_minutes": t,
"needs_projector": pr, "attendees": [{"name": a, "email": None} for a in o]} for n, m, r, d, t, o, pr in PEOPLE]
print(REQUESTS[0]); print(REQUESTS[3])
def toy_prompted(messages, **settings):
"""Stand-in for a model that was only ASKED for JSON. It answers correctly, then applies one typical
drift per request. The mix of drifts is invented for teaching; real rates differ by model and prompt."""
k = int(re.search(r"#(\d+):", messages[-1]["content"]).group(1))
rec, mode = json.loads(json.dumps(GOLD[k])), MODES[k]
if mode == "string_number": rec["duration_minutes"] = str(rec["duration_minutes"])
if mode == "bad_enum": rec["room"] += " Room"
if mode == "extra_key": rec["confidence"] = 0.9
if mode == "missing_key": del rec["requester_email"]
text = json.dumps(rec)
return {"fence": f"```json\n{text}\n```", "prose": f"Here is the JSON you asked for:\n{text}",
"comma": text[:-1] + ",}", "truncated": text[:70]}.get(mode, text)#0: Hi, this is Aiko Tan ([email protected]). Please book Sakura on 2026-11-03 for 45 minutes. Ben Ito and Mei Sato will join. We need a projector.
#3: Hi, this is Priya Nair ([email protected]). Please book Sakura on 2026-11-05 for 2 hours. Nadia Rahman will join. We need a projector.PROMPT = "Extract the meeting request as JSON.\n### REQUEST\n{request}" # the toy ignores the wording; your checks matter here
def classify(text):
try: doc = json.loads(text)
except json.JSONDecodeError as exc: return f"not JSON ({exc.msg})"
return "valid" if not problems(doc) else "schema: " + problems(doc)[0][:48]
client = Client(toy_prompted)
raw = [client.complete([{"role": "user", "content": render(PROMPT, request=r)}]).text for r in REQUESTS]
for k, text in enumerate(raw): print(f"#{k:<2}", classify(text))
print("valid:", sum(classify(t) == "valid" for t in raw), "of", len(raw))#0 valid
#1 not JSON (Expecting value)
#2 valid
#3 not JSON (Expecting value)
#4 not JSON (Expecting property name enclosed in double quotes)
#5 valid
#6 schema: duration_minutes: '30' fails type
#7 schema: room: 'Sakura Room' fails enum
#8 valid
#9 schema: (top): Additional properties are not allowed ('c
#10 schema: (top): 'requester_email' is a required property
#11 not JSON (Expecting ',' delimiter)
valid: 4 of 12Only 4 of 12 are usable, and each failure is different. A syntax parser catches four; the schema catches four more that are valid JSON (wrong type, wrong enum value, extra key, missing key). That is why you validate both. A common patch is to cut the text between the first { and the last }, which removes wrappers but cannot repair content:
from collections import Counter
def extract_json(text):
"""Defensive rescue: keep the text from the first '{' to the last '}'. It removes wrappers; it cannot repair content."""
start, end = text.find("{"), text.rfind("}")
return text[start:end + 1] if 0 <= start < end else text
after = [classify(extract_json(t)) for t in raw]
print("valid after rescue:", after.count("valid"), "of", len(raw))
print(sorted(Counter(a.split(":")[0].split(" (")[0] for a in after if a != "valid").items()))
def toy_constrained(messages, **settings):
"""Stand-in for schema-constrained generation: every reply parses and fits SCHEMA, but a value can still be wrong
(here it reads the first number after 'for', so '2 hours' becomes 2 minutes)."""
k = int(re.search(r"#(\d+):", messages[-1]["content"]).group(1))
rec = json.loads(json.dumps(GOLD[k]))
rec["duration_minutes"] = int(re.search(r"for (\d+)", messages[-1]["content"]).group(1))
return json.dumps(rec)
cons = Client(toy_constrained)
out = [json.loads(cons.complete([{"role": "user", "content": render(PROMPT, request=r)}]).text) for r in REQUESTS]
print("fit the schema:", sum(not problems(d) for d in out), "of", len(out))
print("equal to the true record:", sum(d == g for d, g in zip(out, GOLD)), "of", len(out))
print("wrong duration in requests:", [k for k, (d, g) in enumerate(zip(out, GOLD)) if d != g])valid after rescue: 6 of 12
[('not JSON', 2), ('schema', 4)]
fit the schema: 12 of 12
equal to the true record: 9 of 12
wrong duration in requests: [3, 7, 11]The rescue recovers the fence and the prose-prefix cases and nothing else: 2 replies are still not JSON and 4 still fail the schema. The last three lines show the other half of the lesson: schema-constrained output makes every reply fit the schema, and still gets 3 values wrong (the stand-in reads "2 hours" as 2). Format and truth are separate problems.
Prompted JSON and schema-constrained generation
Prompted JSON is a request in the prompt; the model usually complies and sometimes does not, as above. Schema-constrained generation is a feature of some providers: you pass a schema and the decoder is restricted to output that fits it. State the difference precisely:
| Prompt asks for JSON | Schema-constrained output | |
|---|---|---|
| Parseable, right fields and types | Usually, not guaranteed | Guaranteed when generation completes normally |
| Values correct | No | No: a value can be wrong or invented |
| Always completes | No | No: a refusal or a token-limit cut-off can give output that does not fit; check the stop status before parsing |
| All JSON Schema keywords | Whatever you write (but unenforced) | Only a subset; unsupported keywords may be rejected, so re-check constraints in Python |
Provider note (as of 2026-10-12): OpenAI documents that Structured Outputs ensure schema adherence while JSON mode only ensures valid JSON; that all fields must be required (an optional field is written as a type that allows null), that
additionalPropertiesmust be false, and that some keywords such asallOfandif/then/elseare unsupported; and that a refusal arrives in a separate field and a token-limit cut-off gives an incomplete response. Anthropic documents schema-compliant responses through constrained decoding, no numeric or string-length constraints, and a stop reason ofrefusalormax_tokensthat can yield output that does not match the schema. Google documents a supported subset of JSON Schema, and says to validate values in your application. OpenAI and Google warn that conforming output can still contain wrong values. Limits differ and change: check the current documentation.
So the rule that holds on every provider: whichever way you obtain the JSON, check three things in your own code: the syntax, the schema and the business rules (is the date in the future, does the total add up). The next page, Validation and Repair: jsonschema, Business Rules and Bounded Retries, builds exactly those checks.
Where this shows up at work
Invoice extraction, ticket routing, CRM updates, form filling and any chain stage that feeds code use structured output. Teams usually start with prompted JSON, add schema-constrained output where the provider supports it, and keep their own validation in both cases.
Common mistakes
- Treating "looks like JSON" as valid. Always run a parser and a schema check.
- Letting the model fill missing values. Provide
nullor an explicit unknown and reject look-alike values. - Free labels instead of an enumeration. You get ten spellings of one category. Use a closed list with an escape value.
- Believing constrained output means correct output. It guarantees format only, and not even that after a refusal or a cut-off.
- Deep, rich schemas. Keep them small and flat: fewer places to be wrong, and a better chance of being supported.
Try it yourself
Same session as above.
- Easy. The office adds a fourth room, "Online". Make the schema accept it and show that "online" (lower case) is still rejected. Which line of the prompt must change too?
- Medium. The prompt says
needs_projectorisfalseif not mentioned. Explain why that hides a guess, then change the schema sonullmeans "the request did not say", and testTrue,Noneand"yes". - Hard. Write
parse_strict(text): accept bare JSON, or exactly one fenced block with nothing else; reject everything else with a reason. Run it on replies 0, 1, 3 and 4 from above and say what the policy costs you.
Answers
Easy.
SCHEMA["properties"]["room"]["enum"].append("Online")
print(problems({**good, "room": "Online"}) or "valid", problems({**good, "room": "online"}))valid ["room: 'online' fails enum"]Pass checklist: the new value is added to the schema; the lower-case value is rejected; the room line in the prompt gets the fourth value.
Medium. The prompt forces the model to answer "no" when it does not know, so unknown and "no" look the same. Pass checklist: null is allowed and documented in the prompt as "not said"; a string such as "yes" is rejected; code decides what null means (ask the person, or assume no).
SCHEMA["properties"]["needs_projector"] = {"type": ["boolean", "null"]} # null = the request did not say
for v in (True, None, "yes"):
print(repr(v), problems({**good, "needs_projector": v}) or "valid")True valid
None valid
'yes' ["needs_projector: 'yes' fails type"]Hard.
def parse_strict(text):
"""Accept bare JSON, or ONE fenced block with nothing else around it. Return (document, note)."""
body = text.strip()
fenced = re.fullmatch(r"```(?:json)?\n(.*)\n```", body, re.S)
try: return json.loads(fenced.group(1) if fenced else body), "fenced" if fenced else "clean"
except json.JSONDecodeError as exc: return None, f"rejected: {exc.msg}"
for k in (0, 1, 3, 4):
print(k, *parse_strict(raw[k])[1:])0 clean
1 fenced
3 rejected: Expecting value
4 rejected: Expecting property name enclosed in double quotesPass checklist: bare JSON and a lone fence are accepted (the fence is flagged); prose before the JSON and a trailing comma are rejected with the parser's reason; nothing is guessed. The cost: replies that a rescue function could save are rejected, so you retry or stop. That is a deliberate choice, and the page after this one shows bounded retries.
Summary
- Use free-form text for people and structured output for code; write the prompt as a specification: exact names, required and optional fields, types, enumerations with an escape value, explicit null.
- Prefer required-but-nullable fields to optional ones; reject look-alike missing values with patterns and minimums.
- Ask for the JSON only, without Markdown wrappers, and still parse and validate: a prompt is a request, not a guarantee.
- Schema-constrained generation guarantees format, not truth, can fail on a refusal or a cut-off, and supports only a subset of JSON Schema.
- Always check syntax, schema and business rules in your own code.
Next: Validation and Repair: jsonschema, Business Rules and Bounded Retries, where you build those checks and a safe, bounded repair loop.

