All chapters
  1. Start hereParseable is not valid. Valid is not correct
  2. Foundations · 1From free text to fields and records: why contracts matter
  3. Foundations · 2Syntax, schema, semantics, business validity: four different kinds of right
  4. Foundations · 3JSON and JSON Schema: types, enums, nullable fields, unions and nested objects
  5. Building · 4Typed models: Pydantic in Python, records and Bean Validation in Java
  6. Building · 5Provider output modes: prompting, JSON mode, constrained decoding and tool arguments
  7. Building · 6Tool input, tool result, agent handoff, final response: four contracts on one path
  8. Building · 7Schema design: names, required or optional, and where each value came from
  9. Operating · 8Validation stages: parse, schema, cross-field, domain rules
  10. Operating · 9Errors and repair: retry, clarify, correct within bounds, fall back
  11. Operating · 10Schema evolution: versions, compatibility and migrations
  12. Operating · 11Security: a valid string can still be an attack
  13. Operating · 12Observing contracts: validation failures, schema drift and replay artifacts
  14. Operating · 13Testing contracts: golden examples, property-based tests, fuzzing and contract suites
  15. Reference · 14Frameworks and standards: what each one checks for you
  16. Reference · 15Advanced: partial objects in a stream, polymorphism, multilingual data and typed events
  17. Reference · 16The insurance lab: one submission, four contracts, end to end
  18. ReferenceGlossary
  19. AboutAbout this site and its sources
Foundations · 3

JSON and JSON Schema: types, enums, nullable fields, unions and nested objects

What JSON can and cannot say, and how JSON Schema describes a shape: required, enum, null versus absent, unions with a discriminator, nested objects and arrays, and closed objects.

What you will understand
What JSON can say
Six kinds of value, and the things a model needs that JSON has no word for: dates, units, comments.
Absent, null, zero
Three different answers to "how old is the roof?", and the two keywords that tell them apart.
One of several shapes
Unions and the discriminator field that says which shape a value claims to be.
Open or closed
Why JSON Schema allows any extra key by default, and why every contract here closes the object.

The roof-data provider answers the underwriting agent about submission SUB-1004. On a good day the tool result looks like this:

{"status": "ok", "submission_id": "SUB-1004", "roof_age_years": 22, "source": "roof-data provider (stand-in)", "evidence_id": "EV-ROOF-0412", "method": "aerial image, synthetic"}

For submission SUB-1003 (the facts of the shared case UW-003) the provider has no record. Now think about what the field roof_age_years should hold. A program reading the result can meet it in four states: the key is there with 22, the key is there with 0, the key is there with null, or the key is not there at all. To a person, three of those look like "no age". To the policy fixture (the illustrative rule set of the example) they mean three different things. 0 is a brand-new roof and passes every roof rule. null means "nobody knows", which rule R-ROOF-02 turns into a request for the roof age. A missing key means the producer forgot the field, which is a bug in the producer and not a fact about the roof.

If the contract cannot tell those apart, the workflow cannot either. The roof of SUB-1003 would be approved as new because a converter turned "unknown" into zero. The model recommends; a person decides, but the underwriter would see a confident reason built on a number nobody gave.

The four layers page said that layer 2, the schema, checks the agreed shape. This page is about the language that writes the shape down: what JSON itself can express, and how JSON Schema says required, nullable, one of a fixed list, one of several shapes, and nothing else.

What JSON can say, and what it cannot#

Plain English. JSON is a text format with six kinds of value. Four are simple: a string ("escalate"), a number (0.62), a boolean (true or false) and null. Two hold other values: an object ({"roof_age_years": 22}, named values between curly brackets) and an array (["R-ROOF-03"], a list between square brackets). RFC 8259, the standard that defines JSON, lists exactly these: four primitive types and two structured types.

That short list is the vocabulary every contract on this site is built from, and it is worth noticing what is not in it.

A model needs to sayJSON hasSo the contract does this
A date or a timeno date typean agreed string format, such as "2026-07-01"
A unit (years, square feet, dollars)no unitsthe unit goes into the field name: roof_age_years, area_sq_ft
An integer versus a decimalone number typethe schema says integer where a whole number is meant
A very large or very precise numbernumbers of any length in the text, but readers differkeep integers inside the interoperable range; money as integer cents or dollars
A note to the readerno commentsa description in the schema, never a comment in the data
"This value is unknown"nulldecide per field what null means, and write it down

Two rows deserve a sentence each. RFC 8259 says implementations may "set limits on the range and precision of numbers accepted", and that integers in the range [-(2**53)+1, (2**53)-1] "are interoperable in the sense that implementations will agree exactly on their numeric values". A JavaScript reader stores every number as a double, so a long id written as a number can arrive changed. Ids are strings in every contract here ("SUB-1004"), for that reason and because nobody does arithmetic on them. And the RFC's grammar has no comment syntax at all; a parser that accepts // note is using an extension the RFC allows parsers to accept, not JSON.

Before AI. A relational table has a DATE column, a NUMERIC(12,2) column and a NOT NULL constraint, and a Java class has LocalDate and BigDecimal. JSON has none of these. When a Spring service sends a LocalDate as JSON, Jackson writes a string and the reader has to know which format; the knowledge lives in the code on both sides. With a model as producer there is no code on the producing side, so that knowledge must live in the contract, where the model can read it and the validator can check it.

JSON Schema: a shape written as JSON#

Plain English. A schema is a description of a shape that a program can check. JSON Schema writes that description in JSON itself: an object whose keys are rules. For example, {"type": "integer", "minimum": 0} says "a whole number, zero or more". The JSON Schema project describes it as "a declarative language for defining structure and constraints for JSON data", and the four layers page showed what that word "structure" leaves out.

Each rule is called a keyword. A validator reads the schema and the value and returns an error for every keyword the value breaks. The value being checked is called the instance in the standard's own vocabulary. The current version of the standard is 2020-12, and every schema in examples/uw-contracts/schemas/ declares it in its $schema line.

The smallest useful schema has three keywords:

{"type": "object", "required": ["recommendation"], "properties": {"recommendation": {"type": "string", "enum": ["approve", "decline", "request_info", "escalate"]}}}

Read it from the outside in. The value must be an object. It must contain the key recommendation. If that key is there, its value must be a string and one of four words. The rest of this page adds keywords one at a time, each because a case in the example needs it.

Common confusion. properties does not make a key required. It says "if this key is present, here is the rule for its value". The JSON Schema documentation says it plainly: "By default, the properties defined by the properties keyword are not required." A schema with a long properties list and no required accepts {}.

Types: the first thing a validator checks#

The keyword type names one of the JSON kinds: "string", "number", "boolean", "null", "object", "array", plus "integer". The validation specification defines integer as a type "which matches any number with a zero fractional part". So 1.0 counts as an integer under JSON Schema, and the example's validator follows that rule (minischema.py, function json_type).

type may also be a list. {"type": ["integer", "null"]} accepts a whole number or null and nothing else. That one line is how a field becomes nullable, and it brings us back to the roof.

Absent, null and zero: three answers to one question#

Plain English. Three words, three different rules. A field is required when its key must be present. It is optional when its key may be left out. It is nullable when its value may be null. They are independent: a field can be required and nullable at once. That is the design of roof_age_years in the submission: the key must always be there, so the intake agent cannot forget it, and its value may be null, so the agent can say "nobody said".

The JSON Schema documentation states the principle in one sentence: "In JSON, null isn't equivalent to something being absent." The two are checked by two different keywords. required checks presence. type checks the value, and null is a value.

The demonstration runs five versions of the SUB-1004 submission sample through the example's validator. It proves that the schema separates presence from value, and accepts 0 and null alike; it does not prove which of the two is true for a given roof.

import json
from minischema import validate
from validate import load_schema

schema = load_schema("submission.v1")
base = json.load(open("schemas/samples/submission.v1.sample.json"))

variants = {
    "roof_age_years: 9": dict(base, roof_age_years=9),
    "roof_age_years: null": dict(base, roof_age_years=None),
    "roof_age_years: 0": dict(base, roof_age_years=0),
    "roof_age_years absent": {k: v for k, v in base.items() if k != "roof_age_years"},
    'roof_age_years: "unknown"': dict(base, roof_age_years="unknown"),
}
for label, value in variants.items():
    errors = validate(value, schema)
    print(f"{label:<28}", "schema-valid" if not errors else errors)

Output of a real run in a scratch copy of examples/uw-contracts (the model here is a scripted stand-in, so these results show how the mechanism works, not how good any model is; this demonstration calls no model at all):

roof_age_years: 9            schema-valid
roof_age_years: null         schema-valid
roof_age_years: 0            schema-valid
roof_age_years absent        [{'path': '', 'keyword': 'required', 'message': 'missing required property "roof_age_years"'}]
roof_age_years: "unknown"    [{'path': '/roof_age_years', 'keyword': 'type', 'message': 'expected integer or null, got string'}]

Two results matter. The absent key fails required at the root (path is the empty string, the whole document), and the string fails type at the field. Both are shape problems, so both belong to this layer. And 0 and null both pass. That is the honest limit of a schema: it can make the producer choose between "a number of years" and "unknown", but it cannot know which one the email supports. Case UW-S17, one of this site's own UW-S cases (scripted outputs built on the facts of the series' shared cases), is exactly that: the intake agent writes 0 for a roof the email never mentions. The schema passes it; the provenance check (where did this value come from?) catches it, as schema design shows.

Diagram: Four states of one field · which check can tell them apart

Read left to right: the same field, roof_age_years, in four states. required separates the absent key from the rest. type separates a value that is not a number. 0 and null both pass the schema; only the source of the value can say which one is true.

  1. Key absent
    1. No key: The producer left the field out. A bug in the producer, not a fact about the roof.
  2. Wrong kind
    1. "unknown": A word where the contract allows a whole number or null.
  3. null
    1. null: An explicit statement: nobody knows the roof age.
  4. A number
    1. 0: A brand-new roof. Passes every roof rule.
    2. 9: A roof age the application states.
  5. Beyond the schema
    1. Provenance check: Only a check that reads the source of the value can tell an honest 0 from a guessed one.

Read the diagram as four boxes for one field. The two on the left are separated by required; the middle two by type; the last two only by a check that knows the source of the value.

In our insurance agent. The submission has 63 fields, and the field catalog (field_catalog.json) records for each one whether it is required and whether it is nullable, separately. The catalog generates submission.v1.json, so the two decisions cannot drift apart in two hand-written files.
Production pitfall. A converter that turns null into a default (0, "", false) before validation erases the distinction the contract was built to keep. The typed models page shows one Java configuration that does exactly this with no error.

Enum and const: a fixed list of words#

Plain English. An enum is a fixed list of allowed values. The recommendation may be one of four words, and approved is not one of them. The JSON Schema documentation says enum must be "an array with at least one element, where each element is unique". Its sibling const is "used to restrict a value to a single value": the recommendation record uses "requires_human": {"const": true}, because there is exactly one allowed answer.

An enum turns a sentence into a switch. The cockpit routes on recommendation with a lookup, not with text matching. The comparison is exact: "approved", "Approve" and "approve " (with a trailing space) are all different from "approve". That strictness is the point, and it is also the most common schema failure in this example: UW-S04 writes "approved" and UW-S16 writes "approve or escalate".

Common confusion. An enum checks spelling, not meaning. "decline" passes the enum whether or not any rule supports a decline. UW-S10 is a schema-valid decline of a clean risk; only the domain stage can see that it is false.

Arrays and nested objects#

A field can hold a list or a whole object. reasons is an array of strings; provenance in the submission is an object whose values are themselves objects. Two keywords handle this. items gives the schema every element of an array must match. properties inside a property gives the rule for an object nested inside an object. The validator walks the whole tree and reports each error with a JSON Pointer to where it sits, such as /citations/0 for the first citation (validation is the home of the pointer and the error record).

Arrays have their own size keywords: minItems and maxItems. In recommendation.v1.json, reasons has "minItems": 1, "maxItems": 6: at least one sentence, so a recommendation always says why, and at most six, so the cockpit never shows a page of prose. Strings have minLength, maxLength and pattern. Every citation must match ^R-[A-Z]+-[0-9]{2}$, the shape of a rule id. Numbers have minimum and maximum: stated_confidence lies between 0 and 1.

A nested type earns its place when several fields belong to one thing. The provenance of one value is a source, an evidence id and a quote: three fields that only make sense together. They are a nested object, defined once and reused.

$ref and $defs: one definition, used in several places#

Plain English. $defs is a place inside a schema to keep sub-schemas with names. $ref points at one of them. {"$ref": "#/$defs/provenance_entry"} means "here, the rule called provenance_entry". The JSON Schema documentation calls $defs "a standardized place to keep subschemas intended for reuse in the current schema document". In the submission schema, provenance is an object whose every value must match #/$defs/provenance_entry; in the recommendation record, human_decision refers to #/$defs/human_decision.

The example's validator supports only references inside the same document (#/$defs/<name>). That is a deliberate limit of a teaching validator, listed in the docstring of minischema.py. A production library resolves references across files and URLs, which brings its own question: which version of the referenced file did this validation read?

Closed objects: why every contract here says additionalProperties false#

Plain English. A closed object accepts only the keys the schema names. Any other key is an error. In JSON Schema the keyword is additionalProperties, and the documentation is explicit about the default: "By default any additional properties are allowed." Setting it to false closes the object.

The default is open for a reason: it lets an old reader accept data from a newer writer that added a field, which matters for evolution. But for a model's output, an open object is a door. UW-S07 adds "premium_usd": 18400 to a recommendation. The agent does not quote prices; the contract has no such field. With an open schema the number passes validation, gets stored with the record, and a downstream screen that shows "all fields" puts a premium in front of the underwriter that no rule and no person produced. With "additionalProperties": false it fails at the schema stage, with an error that names the key.

The demonstration below makes five changes to the valid recommendation of UW-004 at once. It proves that the validator collects every error inside the schema stage in one pass, each with its keyword and its place. It does not prove anything about the meaning of the values that pass.

import json
from minischema import validate
from validate import load_schema

schema = load_schema("recommendation.v1")
good = json.loads(json.load(open("golden/valid/uw004-escalate.json"))["text"])
bad = dict(good)
bad["recommendation"] = "approved"        # a word outside the enum
bad["stated_confidence"] = 1.2            # above the maximum
bad["citations"] = ["roof gap rule"]      # does not match the rule-id pattern
bad["premium_usd"] = 18400                # a key the closed object does not allow
del bad["policy_version"]                 # a required key is absent

print("good:", validate(good, schema))
for e in validate(bad, schema):
    print(f'{e["path"] or "(root)":<22} {e["keyword"]:<22} {e["message"]}')
good: []
(root)                 required               missing required property "policy_version"
/recommendation        enum                   "approved" is not one of "approve", "decline", "request_info", "escalate"
/citations/0           pattern                "roof gap rule" does not match ^R-[A-Z]+-[0-9]{2}$
/stated_confidence     maximum                1.2 is greater than 1
/premium_usd           additionalProperties   property "premium_usd" is not allowed

Five problems, five errors, one re-ask can carry all of them. Notice that additionalProperties reports the extra key at its own path, /premium_usd, so a failure dashboard can count it per field.

Production pitfall. The JSON Schema documentation warns that "additionalProperties only recognizes properties declared in the same subschema as itself", and that combining schemas with allOf "doesn't change that". A team that builds a closed object from two allOf parts finds that each part rejects the other's keys. Write a closed object as one flat properties list, or use the 2020-12 keyword unevaluatedProperties, which this site's teaching validator does not implement.

Try it: change one value and read the errors#

The lab starts from the valid UW-004 recommendation, with the recommendation.v1 schema beside it. Switch on a change, or edit the text yourself, and read the validator's errors: the JSON Pointer, the keyword, the message. Try the null and the absent key one after the other and compare which keyword fails.

The same changes, run one at a time with the example's validator in a scratch copy:

Change to the valid UW-004 recommendationKeyword that failsError message
stated_confidence is "high"type/stated_confidence: expected number, got string
recommendation is "approved"enum/recommendation: "approved" is not one of the four words
policy_version is nulltype/policy_version: expected string, got null
policy_version is absentrequired(root): missing required property "policy_version"
extra key premium_usdadditionalProperties/premium_usd: property "premium_usd" is not allowed
stated_confidence is 1.2maximum/stated_confidence: 1.2 is greater than 1
reasons is []minItems/reasons: needs at least 1 item, has 0
a citation "r-roof-03"pattern/citations/0: "r-roof-03" does not match ^R-[A-Z]+-[0-9]{2}$

Look at rows three and four. A null and an absent key both leave the program without a policy version, and the validator still tells them apart, with two keywords at two paths. A repair message can then say the right thing: "you wrote null" is a different instruction from "you left the field out".

Unions: one field, several shapes#

Plain English. A union is a value that may take one of several shapes. The roof assessment is a natural one. When the provider found the roof, the result has an age and an evidence id. When it found nothing, or timed out, it has neither. Those are two shapes, and a value should match exactly one of them.

JSON Schema has two keywords for this. The documentation defines them: for anyOf, "the given data must be valid against any (one or more) of the given subschemas"; for oneOf, "exactly one of the given subschemas". The smallest union in the example is "type": ["integer", "null"], which is an anyOf written short. The recommendation record uses the long form: "recommendation": {"anyOf": [{"$ref": "#/$defs/recommendation"}, {"type": "null"}]}, because a fallback record carries no recommendation at all.

The discriminator: a field that says which shape this is#

When the shapes are objects, the clean design gives every shape one field with a fixed value that names it. That field is called a discriminator. In the roof assessment it is status: "ok" means the found shape, "not_found" or "timeout" means the empty shape. In JSON Schema the discriminator is not a keyword of its own; it is a pattern: each branch of the oneOf pins status with const or enum.

The demonstration below is a design for this page. The example's own roof_assessment.v1.json is flatter: one object in which roof_age_years and evidence_id are nullable. The union version is stricter, and the demonstration shows what it buys. It proves that the union rejects the two contradictory combinations that the flat schema accepts, and a status the contract does not know (UW-S20).

from minischema import validate

# A design for this page: the roof assessment as a union with a discriminator.
# The example's own roof_assessment.v1 is flatter (one object, roof_age_years nullable).
found = {
    "type": "object", "additionalProperties": False,
    "required": ["status", "roof_age_years", "evidence_id"],
    "properties": {
        "status": {"const": "ok"},
        "roof_age_years": {"type": "integer", "minimum": 0, "maximum": 150},
        "evidence_id": {"type": "string", "pattern": "^EV-ROOF-[0-9]{4}$"},
    },
}
not_found = {
    "type": "object", "additionalProperties": False,
    "required": ["status", "roof_age_years"],
    "properties": {
        "status": {"enum": ["not_found", "timeout"]},
        "roof_age_years": {"type": "null"},
    },
}
schema = {"oneOf": [{"$ref": "#/$defs/found"}, {"$ref": "#/$defs/not_found"}],
          "$defs": {"found": found, "not_found": not_found}}

payloads = {
    "ok, 22 years": {"status": "ok", "roof_age_years": 22, "evidence_id": "EV-ROOF-0412"},
    "timeout, null": {"status": "timeout", "roof_age_years": None},
    "ok, but null": {"status": "ok", "roof_age_years": None, "evidence_id": "EV-ROOF-0412"},
    "timeout, but 22": {"status": "timeout", "roof_age_years": 22},
    "partial (UW-S20)": {"status": "partial", "roof_age_years": 22, "evidence_id": "EV-ROOF-0412"},
}
for label, value in payloads.items():
    errors = validate(value, schema)
    print(f"{label:<18}", "schema-valid" if not errors else [e["message"] for e in errors])
    if errors and label == "ok, but null":
        print("   inside branch 'found':", [e["message"] for e in validate(value, found)])
ok, 22 years       schema-valid
timeout, null      schema-valid
ok, but null       ['matches 0 of 2 shapes; exactly one is required']
   inside branch 'found': ['expected integer, got null']
timeout, but 22    ['matches 0 of 2 shapes; exactly one is required']
partial (UW-S20)   ['matches 0 of 2 shapes; exactly one is required']

The output shows both the value and the cost of a union. The value: "found, but no age" and "timed out, but here is an age" are rejected, and a flat schema with nullable fields would have accepted both. The cost: the error is now "matches 0 of 2 shapes", which says nothing about why. The useful message, "expected integer, got null", is only found by validating against the branch the discriminator names. A good validator, or a good repair message, reads the discriminator first and reports the errors of that branch.

Diagram: A union with a discriminator · read status first, then check one branch

The roof assessment comes in two shapes. The workflow reads the discriminator field status first, picks the one branch it names, and validates the value against that branch only, so the error says what is wrong. A status that names no branch is its own clear error.

  1. In
    1. Tool result: The roof assessment for one submission, written by code outside the workflow.
  2. Read the discriminator
    1. status: One field with a fixed value per shape. Each branch pins it with const or enum.
  3. Validate one branch
    1. Found shape: roof_age_years is an integer and evidence_id is present.
    2. Not-found shape: roof_age_years is null; there is no evidence id.
  4. Out
    1. One shape matched: The value matches exactly one branch, so later code knows which fields exist.
    2. Unknown status: A value the contract does not know. Rejected and counted, never guessed.

The diagram shows that reading order. The workflow reads status first, picks the one branch it names, and validates against that branch alone. A status that names no branch is its own, clear error, and in UW-S20 the run degrades to request_info instead of guessing.

What this is not. A schema describes the shape of the data. Where a tool's input schema is published and how a tool call carries it belong to tools.sammuthu.com. How the instruction that shows the schema to the model is written belongs to prompt.sammuthu.com.
For a coding agent. The same keywords describe a coding agent's report in schemas/change_report.v1.json: risk is an enum of low, medium, high; needs_review is a boolean; files_changed is an array of strings; the object is closed, so a stray "approved_by": "me" fails instead of reaching CI. Review and CI lanes live on diff-to-deploy.sammuthu.com.

How the standards and tools treat these keywords#

JSON Schema is a standard; validators are libraries; model providers are products. This section stays with the standard and one neighbouring standard, and leaves libraries to frameworks and providers to provider modes.

Unknown keywords are not errors. The 2020-12 core specification says "Unknown keywords SHOULD be treated as annotations". A schema with "maxItem": 6 (a typo) validates without complaint and checks nothing. The example's validator does the same and says so in its docstring. A schema needs its own tests: a golden example that must fail because of each keyword, which is the subject of testing.

format is a note by default. The validation specification makes format an annotation unless the implementation is told to assert it; four layers quotes the rule. The example's validator does check date and date-time, and says so. Read your library's setting before you trust "format": "date".

OpenAPI has a discriminator keyword; JSON Schema does not. OpenAPI 3.1.1 builds on JSON Schema: its Schema Object "is a superset of the JSON Schema Specification Draft 2020-12". It adds a Discriminator Object, which "gives a hint about the expected schema of the document", with a propertyName that "SHOULD be required in the payload schema, as the behavior when the property is absent is undefined". It also says the discriminator "MUST NOT change the validation outcome of the schema". In other words, OpenAPI names the pattern this page built by hand, and uses it for speed and for code generation; the oneOf still decides.

oneOf costs more than anyOf. The JSON Schema documentation advises: "Prefer anyOf where possible", because oneOf "requires verification of every sub-schema". With a discriminator pinned by const, the branches cannot overlap, so anyOf gives the same result for less work. The example keeps oneOf in the demonstration because "exactly one" is the promise a reader of the schema should see.

Optional or nullable: which one for a model's output?Required-and-nullable is the safer default when a model fills the field

For data written by code, an optional field is cheap: the code either has the value or leaves the key out. For data written by a model, a missing key is ambiguous. Did the model decide the value was unknown, or did it forget the field? Making the key required and the value nullable removes the ambiguity: the model must write the key, and null is an explicit statement. The cost is a longer object and a model that must write null many times in a 63-field submission.

At least one provider feature pushes the same way for its own reasons. Its documents, read today on the provider modes page, require every property to be listed as required in strict mode and suggest a union with null to emulate an optional value. That is a product constraint, not a law of JSON Schema, but it lands on the same design.

Closed objects versus evolutionA closed consumer breaks when the producer adds a field

A closed object is right for a model's output, which the workflow consumes directly. It is a risk for data passed between services that evolve on different schedules: a consumer that rejects unknown keys breaks the day a producer adds one. The usual answer is to close the object where the producer is untrusted (a model, an outside provider) and to read tolerantly where both sides are code you deploy. Version 2 of the recommendation adds evidence_ids; evolution walks through the producer by reader grid and the expand and contract order that keeps both sides working.

Numbers across languagesSame text, different values in different readers

A JSON number has no fixed size. Python reads 9007199254740993 exactly; a JavaScript reader stores the nearest double, which is a different integer. A decimal such as 0.1 is exact in the text and approximate in every reader that uses binary floating point. The schema cannot prevent either. Three habits keep contracts out of trouble: identifiers are strings with a pattern; money is an integer in the smallest unit you need, with the unit in the field name (building_value_usd); and bounds such as "maximum": 1 are checked by every reader, so a value at the boundary behaves the same in Python and in the cockpit's browser. The example's labs run a JavaScript port of the validator, and scripts/test_schema_core.mjs checks it returns the same errors as the Python one.

Which JSON Schema?Drafts, dialects and subsets

There are several published versions of JSON Schema, and tools support different ones. Every schema here declares "$schema": "https://json-schema.org/draft/2020-12/schema", so a reader knows which rules apply. Model providers accept subsets of JSON Schema for constrained output, each with its own list of unsupported keywords; a schema that is complete for your validator may be rejected or partly ignored by a provider. Keep one full schema as the contract the workflow validates against, and treat whatever is sent to a provider as a second, derived artifact that is tested against the first.

Checklist#

In one breath#

JSON gives you six kinds of value and nothing else, so dates, units and "unknown" must be agreed in the contract. JSON Schema writes that agreement as keywords: type for the kind, required for presence, enum for a fixed list, oneOf with a discriminator for several shapes, and additionalProperties: false to shut the door on anything unplanned. Absent, null and 0 are three different answers, and the schema can force the producer to pick one, but only the source of the value can say which one is true. A schema checks shape, not truth.

The roof result and the recommendation now have shapes a validator can enforce. But a validator returns errors, and a program wants a value it can hold: an object with typed fields that the rest of the code can call. The next page, typed models, puts the same recommendation into a Pydantic model and a Java record, and shows where the two stacks quietly disagree about the same text.