JSON Schema in Practice: Validating Data and Generating Types

What a Contract Solves

JSON Schema answers what syntax validation cannot: whether a field exists, whether its type is right, whether a value is in range. Without it, price arriving as "128.5" or a missing userId surfaces only at runtime as a 500—and neither human review nor intuition-driven testing catches that class of bug.

A Minimal Schema

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "required": ["id", "total"],
  "properties": {
    "id":   { "type": "string", "minLength": 1 },
    "total": { "type": "number", "minimum": 0 },
    "items": { "type": "array", "minItems": 1,
               "items": { "type": "object",
                          "properties": {
                            "sku": { "type": "string" },
                            "price": { "type": "number", "minimum": 0 }
                          }, "required": ["sku", "price"] } },
    "status": { "enum": ["paid", "pending", "cancelled"] }
  }
}

It fixes four hard rules: id/total required, total ≥ 0, items a non-empty array whose elements carry sku+price, and status limited to three values.

Keyword Cheat Sheet

Keyword Purpose
type object/array/string/number/integer/boolean/null
required required field list
properties per-field sub-schemas of an object
items / prefixItems array element schema
enum allowed value set
const fixed value (discriminator)
allOf/anyOf/oneOf combine multiple sub-schemas
$ref reference an already-defined schema (reuse)
format / pattern format and regex constraints

Tightening a Generated Schema

Auto-generation yields loose inference: nullable fields, nullable arrays, and any extra property allowed. Turning it into a contract that rejects bad data takes three moves: put mandatory fields into required; add domain limits (enum/format/minimum/minItems); extract reusable objects into $defs and $ref them.

required Only Guarantees "Key Present"

required says nothing about the value, which is the most misread part:

  • {"id": null} satisfies required: ["id"], but {"id": {"type": "string"}} reports a type error; allowing null means declaring ["string", "null"].
  • {"id": ""} also satisfies required; only minLength: 1 stops it—mandatory is not the same as non-empty.
  • A nested required is checked only when the outer property exists: {"user": {}} reports missing fields inside user, while {} (user absent entirely) does not, unless the outer object also lists user as required.

oneOf: Two Forms That Always Fail

Discriminated unions are written as oneOf with a const discriminator in each branch. Two traps are guaranteed:

The discriminator is not in required. properties constrains keys that appear, not keys that must appear. Given {"to":"a@b.c"} with no type, the email branch still passes (it only requires to), and the sms branch may pass too—both hit, oneOf demands exactly one, and the document fails.

The branches are not mutually exclusive. If the email branch constrains only to and the sms branch only phone, data carrying both satisfies both and fails again. Exclusivity must come from the const discriminator, never from which field is present.

Generating Types From a Schema

Once the schema is the single source of truth, types are just its translation: JSON sample → schema → TypeScript/Go definitions, the first hop through a generator and the second through converters such as schema-to-typescript and schema-to-go.

Inferring types from JSON is fast but reflects one sample, losing absent fields and constraints; deriving from the schema preserves enum/required/nullable, and the generated DTOs share a source with runtime validation—so "the type says required while the validator lets it through" cannot happen.

Landing Checklist

  • One versioned schema per endpoint, reviewed with the code;
  • Start with a generator (JSON → JSON Schema), then add required and domain limits by hand;
  • Runtime validation and type generation share the same schema; discriminated unions always use oneOf + const.

Reproducible Results

JSON Schema is "data describing data"; twenty lines of stdlib show its decision order:

schema = {"type": "object", "required": ["id"], "properties": {"id": {"type": "integer"}}}

def check(obj):
    if not isinstance(obj, dict): return False
    if any(k not in obj for k in schema["required"]): return False
    return isinstance(obj.get("id"), int)

print(check({"id": 1}))      # → True
print(check({"name": "x"}))  # → False (missing required id)
print(check({"id": "x"}))    # → False (id is not an integer)

The three cases map to three verdicts: structure (dict), existence (required), type. Real projects use the jsonschema package, and its order of checks—hence its error messages—matches.

Frequently Asked Questions

What is JSON Schema mainly used for?

It is a standard that describes what JSON data must look like: a node must be a number, an array must have at least one element, a field is required, a value must come from an enum, etc. Typical uses: runtime validation of API request/response, front-end form validation, documenting data contracts, and driving strongly-typed generation (TypeScript/Go types). In essence it lifts 'structure plus constraints' out of code into a reusable, cross-language declaration.

How do I turn a JSON sample into a validating schema?

The fastest path is a 'JSON to Schema' generator (usually built into JSON tool sites, e.g. json-to-jsonschema), which infers types, arrays and nesting from the sample. After generation, tighten it by hand: add enums or format constraints (date-time/email), an explicit required list, minItems on arrays and minimum on numbers—turning loose inference into a strict contract that validation can actually enforce.

When to use oneOf, anyOf and allOf?

They combine sub-schemas differently: allOf requires every sub-schema to hold (stacking constraints—commonly adding extensions to a base object); anyOf accepts any one (loose polymorphism, e.g. 'string or null'); oneOf requires exactly one (strict polymorphism—good for discriminated unions, like distinguishing event payloads by activity.type). For discriminated unions prefer oneOf plus a const discriminator field in each sub-schema so the validator can match precisely.

What is the difference between generating from JSON and from Schema?

The starting points differ: JSON → type infers from an instance—fast but only reflects one sample and misses absent fields and constraints; Schema → type (e.g. json-schema-to-typescript) derives from a contract and preserves enum, required and nullable semantics, yielding cleaner, documented types. In production, treat the Schema as the single source of truth that drives both runtime validation and type generation, avoiding dual maintenance of 'API doc' and DTOs.

← Back to Blog