jsonschema vs @hyperjump/json-schema vs ajv vs z-schema
JSON Schema Validation Libraries for Node.js and Frontend
jsonschema@hyperjump/json-schemaajvz-schemaSimilar Packages:

JSON Schema Validation Libraries for Node.js and Frontend

@hyperjump/json-schema, ajv, jsonschema, and z-schema are JavaScript libraries designed to validate data against JSON Schema specifications. While they share the same core goal, they differ significantly in their adherence to recent standards, performance characteristics, and API design. ajv is the industry standard for speed and widespread adoption, compiling schemas into optimized code. @hyperjump/json-schema is a modern, modular library focused on strict compliance with the latest Draft 2019-09 and 2020-12 specifications, including advanced features like dynamic recursion. jsonschema is a pure JavaScript implementation known for simplicity but lacks support for newer drafts. z-schema was once popular for its validator logic but is now largely unmaintained and deprecated in favor of more robust alternatives.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
jsonschema5,823,2331,87583.5 kB762 years agoMIT
@hyperjump/json-schema0314453 kB711 days agoMIT
ajv014,8621.03 MB3846 months agoMIT
z-schema03491.27 MB28 days agoMIT

JSON Schema Validation: Speed, Standards, and Stability Compared

Validating data structures is a critical part of building reliable web applications. Whether you are checking API responses on the backend or ensuring form inputs match expectations on the frontend, JSON Schema is the universal language for defining these rules. However, not all validators are built the same. Let's look at how ajv, @hyperjump/json-schema, jsonschema, and the legacy z-schema handle real-world engineering challenges.

🚀 Performance Strategy: Compilation vs Interpretation

The biggest difference between these libraries is how they execute validation. Some translate your schema into fast code once, while others read the schema every single time they check data.

ajv compiles schemas into native JavaScript functions. This means the validation logic runs at near-native speed because the library does the heavy lifting upfront.

// ajv: Compile once, validate many times
import Ajv from "ajv";
const ajv = new Ajv();

const schema = { type: "object", properties: { id: { type: "number" } } };
const validate = ajv.compile(schema);

// Extremely fast execution
const valid = validate({ id: 123 }); 

@hyperjump/json-schema uses an interpreter model focused on correctness over raw speed. It traverses the schema dynamically for every validation call to ensure every edge case in the spec is handled correctly.

// @hyperjump/json-schema: Dynamic interpretation
import { validate } from "@hyperjump/json-schema";

const schema = { type: "object", properties: { id: { type: "number" } } };
const instance = { id: 123 };

// Interprets the schema rules on every call
const result = await validate(schema, instance);

jsonschema also interprets the schema on every run. It is written in pure JavaScript without native extensions, making it consistent but slower on large datasets compared to compiled approaches.

// jsonschema: Pure JS interpretation
import { Validator } from "jsonschema";

const validator = new Validator();
const schema = { type: "object", properties: { id: { type: "number" } } };

// Runs interpretation logic for each validation
const result = validator.validate({ id: 123 }, schema);

z-schema historically used a compilation approach similar to ajv but lacks the modern optimizations and maintenance updates. Its performance is generally acceptable for small tasks but falls behind in modern benchmarks.

// z-schema: Legacy compilation
import ZSchema from "z-schema";

const validator = new ZSchema();
const schema = { type: "object", properties: { id: { type: "number" } } };

// Compiles internally but lacks modern speed improvements
const valid = validator.validate({ id: 123 }, schema);

📜 Specification Support: Living Standards vs Legacy Drafts

JSON Schema has evolved significantly. Older libraries stop at Draft 4 or 7, while newer ones support the 2020-12 draft, which includes powerful tools for recursive data structures.

ajv supports drafts up to 2020-12, but often requires adding specific packages for newer keywords. It strikes a balance between stability and modern features.

// ajv: Adding support for newer formats
import Ajv2020 from "ajv/dist/2020";
const ajv = new Ajv2020();

// Supports modern keywords like 'unevaluatedProperties'
const schema = { type: "object", unevaluatedProperties: false };

@hyperjump/json-schema is built from the ground up for the latest standards. It fully supports Draft 2019-09 and 2020-12 out of the box, including complex recursive references that other libraries struggle with.

// @hyperjump/json-schema: Native modern support
import { setMetaSchema } from "@hyperjump/json-schema";
import { DRAFT_2020_12 } from "@hyperjump/json-schema/dialects";

// Explicitly opt-in to the latest dialect
await setMetaSchema(DRAFT_2020_12);

jsonschema is stuck on older drafts (primarily Draft 4). It does not support modern keywords like $defs or dynamic recursion, making it unsuitable for complex, nested data models.

// jsonschema: Limited to older keywords
// This modern keyword will be ignored or cause an error
const schema = { 
  type: "object", 
  $defs: { /* Not supported in older drafts */ } 
};

z-schema supports up to Draft 4 reliably. Using it for modern schemas will result in missing validations or errors, as it has not been updated to parse new syntax.

// z-schema: Fails on modern syntax
// Will not recognize 'if'/'then'/'else' constructs properly
const schema = { 
  if: { type: "number" }, 
  then: { minimum: 0 } 
};

🛠️ Error Handling and Output Detail

When validation fails, you need to know exactly why. The quality of error messages varies wildly between these tools.

ajv provides detailed error objects by default, including the data path and schema path. You can easily map these to UI form fields.

// ajv: Detailed error list
if (!validate({ id: "not-a-number" })) {
  console.log(validate.errors);
  // Output: [{ keyword: 'type', instancePath: '/id', message: 'must be number' }]
}

@hyperjump/json-schema returns a rich result object that includes annotations and detailed output formats compliant with the specification's output modes (flag, basic, detailed).

// @hyperjump/json-schema: Spec-compliant output
const result = await validate(schema, { id: "fail" });
if (!result.valid) {
  // Access detailed annotation output
  console.log(result.output);
}

jsonschema returns a simple object with an errors array. The messages are readable but less structured than ajv, sometimes requiring extra parsing to locate the exact field in a deep object.

// jsonschema: Basic error array
const result = validator.validate({ id: "fail" }, schema);
if (!result.valid) {
  console.log(result.errors); 
  // Output: [{ property: 'instance.id', message: 'is not of a type(s) number' }]
}

z-schema provides error messages, but the format is inconsistent by modern standards. It often lacks the precise pointer paths needed for automated UI error mapping.

// z-schema: Legacy error format
const valid = validator.validate({ id: "fail" }, schema);
if (!valid) {
  console.log(validator.getLastErrors());
  // Output format varies and may lack precise JSON pointers
}

⚠️ Maintenance and Future Proofing

Choosing a library is also about choosing its future. Is the project active? Is it secure?

ajv is heavily maintained and widely used in major frameworks (like Fastify and ESLint). It receives regular security patches and feature updates.

@hyperjump/json-schema is actively developed by a team dedicated to pushing the JSON Schema standard forward. It is the safest bet for long-term projects needing cutting-edge spec support.

jsonschema receives occasional updates but development has slowed. It remains stable for its specific niche (pure JS, old drafts) but is not evolving with the web.

z-schema is effectively deprecated. The repository sees little to no activity, and it does not support modern Node.js versions well. Using it introduces technical debt and security risks.

🌐 Real-World Scenarios

Scenario 1: High-Traffic API Gateway

You are validating thousands of incoming requests per second.

  • ✅ Best choice: ajv
  • Why? The compilation model ensures minimal CPU overhead per request.
// Pre-compile schemas at startup
const validateRequest = ajv.compile(apiSchema);

// In request handler
if (!validateRequest(req.body)) {
  return res.status(400).json(validateRequest.errors);
}

Scenario 2: Complex Recursive Data (e.g., File Systems, Comments)

Your data structure references itself deeply, using the latest 2020-12 standard features.

  • ✅ Best choice: @hyperjump/json-schema
  • Why? It handles $dynamicRef and recursive anchors correctly where others fail.
// Define a recursive node structure
const schema = {
  $schema: "https://json-schema.org/draft/2020-12/schema",
  $id: "node",
  type: "object",
  properties: {
    children: { $ref: "node" } // Dynamic recursion
  }
};

// Validates deeply nested structures accurately
await validate(schema, complexTreeData);

Scenario 3: Simple Browser Script with No Build Step

You need a quick validator in a legacy HTML file without npm or bundlers.

  • ✅ Best choice: jsonschema
  • Why? It works via a simple script tag and has no build dependencies.
<!-- Legacy HTML inclusion -->
<script src="node_modules/jsonschema/lib/index.js"></script>
<script>
  const v = new jsonschema.Validator();
  // Simple validation logic
</script>

Scenario 4: Maintaining a 2015 Enterprise App

You are stuck on an old codebase using z-schema.

  • ✅ Action: Plan migration to ajv.
  • Why? z-schema is a ticking time bomb for compatibility issues.
// Migration path: Replace z-schema usage
// OLD: const valid = validator.validate(data, schema);
// NEW: 
const ajv = new Ajv();
const validate = ajv.compile(schema);
const valid = validate(data);

📊 Summary Table

Featureajv@hyperjump/json-schemajsonschemaz-schema
Execution⚡ Compiled (Fastest)🧠 Interpreted (Accurate)🐢 Interpreted (Slow)⚙️ Compiled (Legacy)
Max Draft2020-12 (via config)2020-12 (Native)Draft 4/7Draft 4
Recursive RefsLimited✅ Full Support ($dynamicRef)❌ No❌ No
Maintenance🟢 Active🟢 Active🟡 Stable/Legacy🔴 Deprecated
Bundle SizeMedium (Optimizable)Larger (Modular)SmallMedium
Use CasePerformance CriticalComplex/Modern SchemasSimple/Legacy JSDo Not Use

💡 Final Recommendation

For most professional frontend and backend teams, ajv is the default choice. Its speed and ecosystem support make it the practical standard for 90% of use cases. If you are building tools that rely on the absolute latest JSON Schema features or need to validate highly recursive data structures strictly according to the 2020-12 spec, @hyperjump/json-schema is the superior architectural choice. Avoid jsonschema unless you have a specific constraint requiring pure JS without dependencies, and remove z-schema from any new design immediately.

How to Choose: jsonschema vs @hyperjump/json-schema vs ajv vs z-schema

  • jsonschema:

    Choose jsonschema only for legacy projects or simple use cases where you need a zero-dependency, pure JavaScript validator for older drafts (Draft 4-7). It is suitable for small scripts, educational purposes, or environments where installing native binaries or complex dependencies for other libraries is impossible, but avoid it for new production systems requiring modern schema features.

  • @hyperjump/json-schema:

    Choose @hyperjump/json-schema if your project requires strict compliance with the latest JSON Schema drafts (2019-09 or 2020-12), especially if you need advanced features like $dynamicRef for recursive schemas. It is ideal for architectural contexts where specification accuracy matters more than raw throughput, such as API gateways enforcing complex contracts or tools generating documentation from schemas.

  • ajv:

    Choose ajv if performance is your top priority and you are working with standard drafts (up to Draft 2020-12 with plugins). It is the best fit for high-volume data processing, real-time validation in user interfaces, or backend services where latency matters. Its ability to compile schemas into standalone JavaScript functions makes it unique for bundling validation logic into lightweight frontend bundles.

  • z-schema:

    Do NOT choose z-schema for new projects. It is effectively deprecated and unmaintained, lacking support for modern JSON Schema drafts and security patches. If you encounter it in an existing codebase, plan a migration to ajv or @hyperjump/json-schema immediately to ensure reliability and access to current web standards.

README for jsonschema

Build Status

jsonschema

JSON schema validator, which is designed to be fast and simple to use. JSON Schema versions through draft-07 are fully supported.

Contributing & bugs

Please fork the repository, make the changes in your fork and include tests. Once you're done making changes, send in a pull request.

Bug reports

Please include a test which shows why the code fails.

Usage

Simple

Simple object validation using JSON schemas.

var Validator = require('jsonschema').Validator;
var v = new Validator();
var instance = 4;
var schema = {"type": "number"};
console.log(v.validate(instance, schema));

Even simpler

var validate = require('jsonschema').validate;
console.log(validate(4, {"type": "number"}));

Complex example, with split schemas and references

var Validator = require('jsonschema').Validator;
var v = new Validator();

// Address, to be embedded on Person
var addressSchema = {
  "id": "/SimpleAddress",
  "type": "object",
  "properties": {
    "lines": {
      "type": "array",
      "items": {"type": "string"}
    },
    "zip": {"type": "string"},
    "city": {"type": "string"},
    "country": {"type": "string"}
  },
  "required": ["country"]
};

// Person
var schema = {
  "id": "/SimplePerson",
  "type": "object",
  "properties": {
    "name": {"type": "string"},
    "address": {"$ref": "/SimpleAddress"},
    "votes": {"type": "integer", "minimum": 1}
  }
};

var p = {
  "name": "Barack Obama",
  "address": {
    "lines": [ "1600 Pennsylvania Avenue Northwest" ],
    "zip": "DC 20500",
    "city": "Washington",
    "country": "USA"
  },
  "votes": "lots"
};

v.addSchema(addressSchema, '/SimpleAddress');
console.log(v.validate(p, schema));

Returned ValidatorResult object, will show this example is NOT valid since: "votes": "lots" is not an integer.

Example for Array schema

var arraySchema = {
        "type": "array",
        "items": {
            "properties": {
                "name": { "type": "string" },
                "lastname": { "type": "string" }
            },
            "required": ["name", "lastname"]
        }
    }

For a comprehensive, annotated example illustrating all possible validation options, see examples/all.js

Features

Definitions

All schema definitions are supported, $schema is ignored.

Types

All types are supported

Handling undefined

undefined is not a value known to JSON, and by default, the validator treats it as if it is not invalid. i.e., it will return valid.

var res = validate(undefined, {type: 'string'});
res.valid // true

This behavior may be changed with the "required" option:

var res = validate(undefined, {type: 'string'}, {required: true});
res.valid // false

Formats

Disabling the format keyword.

You may disable format validation by providing disableFormat: true to the validator options.

String Formats

All formats are supported, phone numbers are expected to follow the E.123 standard.

Custom Formats

You may add your own custom format functions. Format functions accept the input being validated and return a boolean value. If the returned value is true, then validation succeeds. If the returned value is false, then validation fails.

  • Formats added to Validator.prototype.customFormats do not affect previously instantiated Validators. This is to prevent validator instances from being altered once created. It is conceivable that multiple validators may be created to handle multiple schemas with different formats in a program.
  • Formats added to validator.customFormats affect only that Validator instance.

Here is an example that uses custom formats:

Validator.prototype.customFormats.myFormat = function(input) {
  return input === 'myFormat';
};

var validator = new Validator();
validator.validate('myFormat', {type: 'string', format: 'myFormat'}).valid; // true
validator.validate('foo', {type: 'string', format: 'myFormat'}).valid; // false

Results

By default, results will be returned in a ValidatorResult object with the following properties:

  • instance: any.
  • schema: Schema.
  • errors: ValidationError[].
  • valid: boolean.

Each item in errors is a ValidationError with the following properties:

  • path: array. An array of property keys or array offsets, indicating where inside objects or arrays the instance was found.
  • property: string. Describes the property path. Starts with instance, and is delimited with a dot (.).
  • message: string. A human-readable message for debugging use. Provided in English and subject to change.
  • schema: object. The schema containing the keyword that failed
  • instance: any. The instance that failed
  • name: string. The keyword within the schema that failed.
  • argument: any. Provides information about the keyword that failed.

The validator can be configured to throw in the event of a validation error:

  • If the throwFirst option is set, the validator will terminate validation at the first encountered error and throw a ValidatorResultError object.

  • If the throwAll option is set, the validator will throw a ValidatorResultError object after the entire instance has been validated.

  • If the throwError option is set, it will throw at the first encountered validation error (like throwFirst), but the ValidationError object itself will be thrown. Note that, despite the name, this does not inherit from Error like ValidatorResultError does.

The ValidatorResultError object has the same properties as ValidatorResult and additionally inherits from Error.

"nestedErrors" option

When oneOf or anyOf validations fail, errors that caused any of the sub-schemas referenced therein to fail are normally suppressed, because it is not necessary to fix all of them. And in the case of oneOf, it would itself be an error to fix all of the listed errors.

This behavior may be configured with options.nestedErrors. If truthy, it will emit all the errors from the subschemas. This option may be useful when troubleshooting validation errors in complex schemas:

var schema = {
  oneOf: [
    { type: 'string', minLength: 32, maxLength: 32 },
    { type: 'string', maxLength: 16 },
    { type: 'number' },
  ]
};
var validator = new Validator();
var result = validator.validate('This string is 28 chars long', schema, {nestedErrors: true});

// result.toString() reads out:
// 0: instance does not meet minimum length of 32
// 1: instance does not meet maximum length of 16
// 2: instance is not of a type(s) number
// 3: instance is not exactly one from [subschema 0],[subschema 1],[subschema 2]

Localizing Error Messages

To provide localized, human-readable errors, use the name string as a translation key. Feel free to open an issue for support relating to localizing error messages. For example:

var localized = result.errors.map(function(err){
  return localeService.translate(err.name);
});

Custom keywords

Specify your own JSON Schema keywords with the validator.attributes property:

validator.attributes.contains = function validateContains(instance, schema, options, ctx) {
  if(typeof instance !== 'string') return;
  if(typeof schema.contains !== 'string') throw new jsonschema.SchemaError('"contains" expects a string', schema);
  if(instance.indexOf(schema.contains)<0){
    return 'does not contain the string ' + JSON.stringify(schema.contains);
  }
}
var result = validator.validate("I am an instance", { type:"string", contains: "I am" });
// result.valid === true;

The instance passes validation if the function returns nothing. A single validation error is produced if the function returns a string. Any number of errors (maybe none at all) may be returned by passing a ValidatorResult object, which may be used like so:

  var result = new ValidatorResult(instance, schema, options, ctx);
  while(someErrorCondition()){
    result.addError('fails some validation test');
  }
  return result;

Dereferencing schemas

Sometimes you may want to download schemas from remote sources, like a database, or over HTTP. When importing a schema, unknown references are inserted into the validator.unresolvedRefs Array. Asynchronously shift elements off this array and import them:

var Validator = require('jsonschema').Validator;
var v = new Validator();
v.addSchema(initialSchema);
function importNextSchema(){
  var nextSchema = v.unresolvedRefs.shift();
  if(!nextSchema){ done(); return; }
  databaseGet(nextSchema, function(schema){
    v.addSchema(schema);
    importNextSchema();
  });
}
importNextSchema();

Disallowing unknown attributes

Sometimes you may want to disallow unknown attributes passed in the body of the request, in order to disallow those unknown attributes before the validation of the body, you need to set additionalProperties to false.

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Accounting Resource - Add Item",
  "type": "object",
  "additionalProperties": false,
  "properties": {
      "itemNumber": {
          "type":"string"
      },
      "title": {
          "type":"string"
      },
      "description": {
          "type":"string"
      }
  },
  "required": [
      "itemNumber",
      "title",
      "description"
  ]
}

Default base URI

Schemas should typically have an id with an absolute, full URI. However if the schema you are using contains only relative URI references, the base option will be used to resolve these.

This following example would throw a SchemaError if the base option were unset:

var result = validate(["Name"], {
  id: "/schema.json",
  type: "array",
  items: { $ref: "http://example.com/schema.json#/definitions/item" },
  definitions: {
    item: { type: "string" },
  },
}, { base: 'http://example.com/' });

Rewrite Hook

The rewrite option lets you change the value of an instance after it has successfully been validated. This will mutate the instance passed to the validate function. This can be useful for unmarshalling data and parsing it into native instances, such as changing a string to a Date instance.

The rewrite option accepts a function with the following arguments:

  • instance: any
  • schema: object
  • options: object
  • ctx: object
  • return value: any new value for the instance

The value may be removed by returning undefined. If you don't want to change the value, call return instance.

Here is an example that can convert a property expecting a date into a Date instance:

const schema = {
  properties: {
    date: {id: 'http://example.com/date', type: 'string'},
  },
};

const value = {
  date: '2020-09-30T23:39:27.060Z',
};

function unmarshall(instance, schema){
  if(schema.id === 'http://example.com/date'){
    return new Date(instance);
  }
  return instance;
}

const v = new Validator();
const res = v.validate(value, schema, {rewrite: unmarshall});

assert(res.instance.date instanceof Date);

Pre-Property Validation Hook

If some processing of properties is required prior to validation a function may be passed via the options parameter of the validate function. For example, say you needed to perform type coercion for some properties:

// See examples/coercion.js
function preValidateProperty(object, key, schema, options, ctx) {
  var value = object[key];
  if (typeof value === 'undefined') return;

  // Test if the schema declares a type, but the type keyword fails validation
  if (schema.type && validator.attributes.type.call(validator, value, schema, options, ctx.makeChild(schema, key))) {
    // If the type is "number" but the instance is not a number, cast it
    if(schema.type==='number' && typeof value!=='number'){
      object[key] = parseFloat(value);
      return;
    }
    // If the type is "string" but the instance is not a string, cast it
    if(schema.type==='string' && typeof value!=='string'){
      object[key] = String(value).toString();
      return;
    }
  }
};

// And now, to actually perform validation with the coercion hook!
v.validate(instance, schema, { preValidateProperty });

Skip validation of certain keywords

Use the "skipAttributes" option to skip validation of certain keywords. Provide an array of keywords to ignore.

For skipping the "format" keyword, see the disableFormat option.

Fail on unknown keywords

By default, JSON Schema is supposed to ignore unknown schema keywords.

You can change this behavior to require that all keywords used in a schema have a defined behavior, by using setting the "allowUnknownAttributes" option to false.

This example will throw a SchemaError:

var schema = {
  type: "string",
  format: "email",
  example: "foo",
};
var result = validate("Name", schema, { allowUnknownAttributes: false });

Tests

Uses JSON Schema Test Suite as well as our own tests. You'll need to update and init the git submodules:

git submodule update --init
npm test

Contributions

This library would not be possible without the valuable contributions by:

  • Austin Wright

... and many others!

License

jsonschema is licensed under MIT license.

Copyright (C) 2012-2019 Tom de Grunt <tom@degrunt.nl>

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.