Structured response schemas
A machine-readable answer is not necessarily a correct answer
Structured outputs are responses organized into a known shape, so an application can consume fields instead of guessing where a sentence ends. Imagine a fictional stockroom receiving the note “P1: two boxes.” A response containing item P1, quantity 2 and unit box is useful only if the fields have the expected types and reflect the note. Separate three gates: parse the text as JSON, validate its shape, then verify its meaning against trusted evidence. Schema-constrained generation can reduce malformed outputs, but availability and supported keywords depend on the selected model and API. Do not equate ordinary JSON mode with schema conformance. Even schema-constrained responses may be incomplete or refusals; handle the provider envelope before parsing. No model account is required for this lesson.
Parse without silently accepting ambiguous records
JSON objects map string keys to values; strings, numbers, arrays, objects, booleans and null are distinct JSON values. Python json.loads converts a JSON document into Python values. A truncated object raises an error, but default Python decoding accepts repeated keys with the last value winning and accepts nonstandard NaN and Infinity tokens. Our small offline parser rejects both explicitly. It does not repair malformed input or claim comprehensive hardening. The first printed line contains the parsed dictionary; the second reports rejection of repeated quantity. Production code should cap bytes and nesting, isolate parsing and handle resource errors; this example accepts only small trusted test fixtures.
import json
def parse_record(text): def unique_pairs(pairs): result = {} for key, value in pairs: if key in result: raise ValueError("duplicate key") result[key] = value return result def reject_constant(value): raise ValueError("non-JSON constant") return json.loads(text, object_pairs_hook=unique_pairs, parse_constant=reject_constant)
print(parse_record('{"item":"P1","quantity":2}'))try: parse_record('{"item":"P1","quantity":2,"quantity":3}')except ValueError: print("Rejected ambiguous record")Describe the expected shape with JSON Schema
The following is a standalone Draft 2020-12 schema, not a provider request payload. properties describes each allowed field, required requires its presence, and additionalProperties: false rejects unexpected keys. An enum restricts a value to listed choices. Null explicitly represents missing information in this teaching contract; omitting a required field is different. Minimum and maximum bound numeric values. Some providers support only a subset of JSON Schema, so verify their exact accepted dialect and constraints before sending this schema. A schema validator must understand the declared dialect.
{ "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": { "item": { "type": [ "string", "null" ], "minLength": 1 }, "quantity": { "type": [ "integer", "null" ], "minimum": 1, "maximum": 100 }, "unit": { "enum": [ "piece", "box", null ] } }, "required": [ "item", "quantity", "unit" ], "additionalProperties": false}Implement a narrower application contract
The next function validates an already parsed record and returns error labels in a fixed order. The application requires native Python integers, not numeric strings or booleans. Python bool is a subclass of int, so type(q) is int deliberately excludes True. JSON Schema integer is defined by mathematical value, so a JSON number such as 2.0 can satisfy that type; our stricter Python rule rejects the decoded float. This is a hand-written contract checker, not a general JSON Schema implementation. The first record has no errors. The second reports quantity and unit because it supplies a string and an unsupported unit. A null is shape-valid but must be reviewed before use. Exact keys prevent an unexpected field from quietly flowing into downstream code.
def shape_errors(record): if type(record) is not dict: return ["object_required"] if set(record) != {"item", "quantity", "unit"}: return ["fields"] errors = [] if record["item"] is not None and (type(record["item"]) is not str or not record["item"]): errors.append("item") q = record["quantity"] if q is not None and (type(q) is not int or not 1 <= q <= 100): errors.append("quantity") if record["unit"] not in ("piece", "box", None): errors.append("unit") return errors
print(shape_errors({"item":"P1", "quantity":2, "unit":"box"}))print(shape_errors({"item":"P1", "quantity":"2", "unit":"kg"}))Practice and common mistakes
Predict the errors for quantity True, 0, 100, 101 and null, and for a missing unit. Do not coerce every string into an integer; that can hide extraction failures or change the contract. Do not replace missing fields with zero. For small fixed-form records, a deterministic parser may be preferable to an LLM; use a model only when variable wording requires it and verify results. Continue to semantic validation before showing a draft. Reference: JSON Schema object and numeric types documentation; Python json library documentation. The lab contains the original schema fixture.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Structured response schemas quiz
Apply the validation contract to synthetic stockroom records.
What does successful JSON parsing establish?
Which schema keyword requires a named property to be present?
Why is quantity null different from a missing quantity field?
What happens to quantity True in the Python shape checker?
Which statement about JSON number 2.0 is correct here?