Generate validators from JSON Schema

What generating a validator from JSON Schema changes, when it suits your project, when plain runtime validation is simpler, and what to check before sharing generated code.

Generating a validator from JSON Schema means turning a schema document into executable checking logic, either compiled in memory when your program starts or written out as source code you ship with your project. This review explains what that step changes, when it is worth doing, and where a simpler approach is enough. No specific tools were tested for this article, so it covers documented principles rather than measured results.

Is a generated validator the right fit?

A generated validator suits you if you have a fairly stable schema, validate the same kind of data repeatedly, and want the checks to run in a specific language or without loading the schema at runtime. The main benefit is that one schema becomes the single source of truth for what valid data looks like, and the checks run as ordinary code.

The decisive tradeoff is coupling. Generated code is a snapshot of the schema and of the generator version that produced it. When either changes, you have to regenerate, and generators differ in which schema drafts and keywords they fully support. If a generator quietly ignores a keyword it does not implement, the validator can accept data that the schema was meant to reject.

A plainer approach is better in three situations. For one-off checks, pasting the data into an online or command-line validator that interprets the schema directly is quicker. If the schema changes often, validating at runtime against the current schema file avoids a regeneration step. And if the goal is only to help people read the data, formatted JSON or a short plain-text description of the required fields is clearer than any generated code.

What generation actually changes

Generation changes your code, not your data. The schema is translated into functions that inspect a JSON value and report whether it conforms. The JSON being checked is not reformatted, reordered or rewritten by validation alone. This is the main difference from a formatter, which changes only whitespace and indentation and says nothing about whether the structure is correct.

There is one important exception. Some validator libraries offer options that do modify the input, such as filling in default values, removing properties the schema does not allow, or converting types like the string "42" into the number 42. These options are typically off by default and are useful in some pipelines, but once enabled, the validator becomes a transformation step. Check the configuration before assuming the data you validated is the data you received.

The word "generator" is used for several different tools, which causes confusion:

Approach | What you get | When checks run | Main tradeoff
Runtime compilation | A validation function built in memory from the schema | Each time the program starts, then on every check | Needs the validator library and schema at runtime
Ahead-of-time code generation | Source files containing the validation logic | At build time for generation, then on every check | Must be regenerated whenever the schema changes
Type or model generation | Type definitions or data classes in a programming language | Mostly at compile time or object construction | Static types alone do not check incoming JSON at runtime
Schema inference | A draft schema guessed from sample JSON | Once, when you generate it | Reflects only the samples, so it needs manual review

Only the first two produce validators in the strict sense. Generated types are helpful for editor support, but a type declaration in a compiled language does not by itself reject a malformed API response. Schema inference works in the opposite direction from validator generation: it creates a schema from data rather than checks from a schema.

The schema's draft also matters. JSON Schema has several published versions, including draft-04, draft-06, draft-07, 2019-09 and 2020-12, and the $schema keyword declares which one a document uses. Keywords and their behavior differ between drafts. For example, in 2019-09 and later the format keyword is treated as an annotation by default, so a value like "not-an-email" may pass a "format": "email" check unless the validator is configured to enforce formats. Confirm that the generator supports your declared draft and how it handles format.

A small example shows what a validator checks. Given this schema and input, a conforming validator should report two problems: the required email property is missing, and age is a string instead of an integer.

Schema:
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "required": ["name", "email"],
  "properties": {
    "name": { "type": "string" },
    "email": { "type": "string", "format": "email" },
    "age": { "type": "integer", "minimum": 0 }
  }
}

Input:
{
  "name": "Ada",
  "age": "36"
}

The input is left unchanged by validation unless type coercion is enabled, in which case some validators would convert "36" to 36 and report only the missing email. The exact wording and number of error messages vary by library.

Will the result stay usable after copying or sharing?

There are two things that get copied and shared: the schema text and the generated validator. Each has its own risks.

Schema and sample JSON copied from documents, chat tools or web pages often pick up characters that break parsing. Common causes include:

  • Curly quotation marks substituted for straight double quotes by word processors or messaging apps
  • Non-breaking spaces or zero-width characters that look like normal spacing but are not valid JSON whitespace
  • A byte order mark at the start of the file, which some parsers reject
  • Comments or trailing commas, which standard JSON does not allow even though some editors tolerate them

If a generator reports a parse error on a schema that looks correct, retyping the quotes or running the text through a strict JSON formatter usually reveals the problem. Keeping the schema as a plain file in version control, rather than pasting it between tools, avoids most of these issues.

Generated validator code is less portable than it looks. It is tied to a target language and sometimes to a specific runtime version. Code described as standalone may still import helper modules from the library that produced it, so check the output's imports before copying it into another project. Generated files are generally not meant to be edited by hand; any manual fix is lost on the next regeneration. Marking the files as generated and recording the generator version alongside them makes later changes easier to trace.

Readability matters most in error output. Validators usually locate errors with a path into the data, such as a JSON Pointer like /age, plus a message tied to the failing keyword. That works for developers but is often unclear to end users. If validation errors reach a form or user interface, translate them into plain language and attach each message to the relevant field as visible text so that screen readers and other assistive technology can announce it. This article does not include testing with any specific screen reader or browser, so treat that as a general practice rather than a verified result for a particular setup.

Search and editing are mostly unaffected, because neither the schema nor the validated data is restructured. The exception is the input-modifying options described above: if defaults are inserted or extra properties removed, what gets stored or searched later may differ from what was submitted.

Checks before adopting a generator

  • Confirm the generator supports the draft declared in your schema's $schema keyword
  • Find out how it handles keywords it does not implement: error, warning or silent skip
  • Decide whether format should be enforced and configure it explicitly
  • Review any options that insert defaults, remove properties or coerce types
  • Check the generated code's dependencies before treating it as self-contained
  • Plan where regeneration happens, such as a build step, so the validator cannot drift from the schema
  • Write a few known-valid and known-invalid samples and run them after every regeneration

What this review could not verify

No specific generator, library or online tool was tested for this article, so there are no performance figures, keyword coverage comparisons or error-message samples from named products. Privacy and data retention practices of online validators and generators also were not reviewed, and they cannot be judged from a tool's appearance or marketing. If your schema or sample data contains sensitive information, check the tool's published policy or use a local option before pasting anything in.