Skip to content
DevTinyTools

Typing

JSON Schema from a sample: what it can prove

Paste two responses and a schema generator writes a document that looks authoritative: required keys, typed fields, nested definitions. Every line is a fact about the sample you gave it, not a promise about the endpoint. Knowing which lines were observed and which were widened is what separates a schema that validates tomorrow's data from one that rejects it.

10 min readTool: JSON to Schema

One record is not a contract

Here are two responses from GET /api/users. The second omits avatarUrl, has a null last-seen time and a fractional score — three ordinary differences that a single-sample generator would get wrong:

[
  { "id": 1042, "email": "ada@example.com", "displayName": "Ada",
    "avatarUrl": "https://cdn.example.com/ada.png", "roles": ["admin", "editor"],
    "lastSeenAt": "2026-11-01T09:30:00Z", "score": 12 },
  { "id": 1043, "email": "alan@example.com", "displayName": "Alan",
    "roles": ["viewer"], "lastSeenAt": null, "score": 9.5 }
]

Fed to the JSON Schema generator, that sample produces this. Read it as a list of decisions the data made on your behalf:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "User",
  "type": "array",
  "items": {
    "$ref": "#/$defs/UserItem"
  },
  "$defs": {
    "UserItem": {
      "type": "object",
      "properties": {
        "id": { "type": "integer" },
        "email": { "type": "string" },
        "displayName": { "type": "string" },
        "avatarUrl": { "type": "string" },
        "roles": { "type": "array", "items": { "type": "string" } },
        "lastSeenAt": { "type": ["string", "null"] },
        "score": { "type": "number" }
      },
      "required": [
        "id", "email", "displayName", "roles", "lastSeenAt", "score"
      ],
      "additionalProperties": false
    }
  }
}

Three lines are worth stopping at. avatarUrl is described but not required, because one record lacked it. lastSeenAt is a union of string and null, because a null actually appeared. And score is number, not integer, because 9.5 ruled the narrower type out.

Required means observed, not promised

The most useful property of a schema generator is also the most misunderstood: required is computed from sample count, not guessed from field names. Paste a single record and every key is required — the tool saw no evidence that any could be absent. Here is the same generator with only the first record:

"avatarUrl": { "type": "string" },   // present in properties
"lastSeenAt": { "type": "string" }, // no null seen
"score": { "type": "integer" },     // no fraction seen
"required": ["id", "email", "displayName", "avatarUrl",
             "roles", "lastSeenAt", "score"]

All three differences point the same way. avatarUrl becomes required, lastSeenAt loses its null arm and score narrows to integer. Each edit makes the schema stricter, and each one would reject a response you already know the endpoint can send. Ten mixed records are worth more than one perfect-looking one.

Six decisions the generator makes for you

Every JSON-to-schema tool answers the same six questions. The output looks different mainly because they answer differently, so these are worth knowing before you trust a result:

Decisions a JSON Schema generator makes from a sample
The sample showsThe schema writesWhat it means
A key is missing from one recordLeft out of requiredCorrect for that sample. If the key is actually always sent, you under-constrained — add it back by hand.
Whole numbers, then one fractioninteger widens to numberinteger would reject the fractional record. Widening keeps the schema valid; narrowing by hand is a real decision.
null appears alongside a typetype: ["string", "null"]null is a value, not an absent key. The union records exactly what the sample contained.
Object or primitive in the same fieldanyOfA primitive-only union fits in a type array; the moment an object joins, the schema needs anyOf.
A nested object shape$defs + $refRepeated shapes are named and referenced, so a change to the shape is made once.
A key no record showedadditionalProperties: falseStrict by default: unknown keys fail validation. Turn it off for responses that gain fields over time.

Widening is the rule that keeps a generated schema usable: an integer becomes number at the first fraction, and a primitive union becomes a compact type array. A union that mixes an object with a primitive cannot use that shorthand, so it becomes anyOf.

Four things the sample cannot tell you

A perfect generator would still stop at four questions. The data does not contain the answers; it is information about your domain, not about this payload.

  • Which keys are truly required. The generator knows which keys were present, not which ones the contract promises. A key in every record of a small sample may still be optional in production.
  • Which numbers are money. A price of 129.5 is just a number. Add a multipleOf rule, or store minor units as integers — the sample cannot tell you which you need.
  • Which strings have a format. An ISO timestamp, an email and a UUID are all string to a generator. format: date-time and pattern are yours to add.
  • Which fields are enums. A status field showing "shipped" becomes string, not a one-value enum. That is the only honest reading of a single observation.

That is why a generated schema is a correct skeleton rather than a finished contract. The mechanical work — required keys, type unions, nested definitions — is done. The four edits above are yours.

Keeping the schema honest after generation

  • Generate from real payloads, not from documentation. Docs describe the intended contract; responses describe what the endpoint returns today. When they disagree, the schema that validates traffic is the one built from traffic.
  • Name the root before you copy. The title becomes the root and prefixes nested definitions — UserItem reads better in an editor than RootItem.
  • Decide strictness per endpoint. additionalProperties: false on a stable internal contract; leave it open on a third-party response that adds fields without notice.
  • Commit the file and let it diff. When the API changes, a regenerated schema shows the change in review. One that is rebuilt invisibly at runtime gives you no such signal.

One trap sits upstream of all of this: if the sample contains a very large integer, JavaScript has already lost its last digits by the time the schema is generated. The number precision guide explains what to check first. For the compile-time half of the same problem, see JSON to TypeScript: your sample is not a schema.

Frequently asked questions

What is a JSON Schema, in one sentence?
A document that describes another JSON document: which keys may appear, which are required, and what type each value must be. Validators read it to accept or reject data, editors read it to autocomplete, and code generators read it to produce types.
Why draft 2020-12, and what are $defs?
2020-12 is the current standard. Nested object shapes are collected under $defs and referenced with $ref — the spelling used from 2019-09 onward. Older drafts called the same thing definitions. Ajv, Python's jsonschema and most editors read 2020-12 directly.
Why is a field in my output optional when I expected it to be required?
Because at least one record in your sample did not carry it. The generator marks a key required only when every sampled element has it. If the field really is always present, add it to required yourself — or repaste a sample that represents the full response.
Should additionalProperties be true or false?
False is the safer default for a fixed contract: a new, unrecognised key fails validation instead of passing silently. Set it to true for responses that gain optional fields over time, where failing on every new field would create constant alert noise.
Can I use the generated schema as an OpenAPI document?
Not directly — a schema has no paths. OpenAPI 3.1 adopts JSON Schema 2020-12 wholesale, so the same shapes can be wrapped in components.schemas and attached to the routes you know. A sample tells you data shapes, never endpoints.
Is a generated schema better than generated TypeScript types?
They solve different halves. Types are checked at compile time and then erased, so they cannot inspect a response from a server you do not control. A schema exists at runtime and can reject a bad response with the failing path. The /json-to-typescript guide covers that boundary in detail.