z-schema vs ajv vs joi vs jsonschema
JSON Schema Validation Libraries
z-schemaajvjoijsonschemaSimilar Packages:

JSON Schema Validation Libraries

JSON schema validation libraries are essential tools in web development for ensuring that JSON data structures conform to defined schemas. They help in validating data formats, types, and structures, which is crucial for maintaining data integrity and preventing errors in applications that rely on JSON for data interchange. These libraries provide various features such as performance optimization, extensibility, and ease of use, catering to different validation needs in both client-side and server-side applications.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
z-schema2,993,9123411.29 MB7a day agoMIT
ajv014,6281.03 MB31715 days agoMIT
joi021,201557 kB1903 months agoBSD-3-Clause
jsonschema01,87083.5 kB68a year agoMIT

Feature Comparison: z-schema vs ajv vs joi vs jsonschema

Performance

  • z-schema:

    z-schema offers good performance and is optimized for speed, particularly when validating large JSON documents. Its asynchronous validation capabilities also enhance performance in scenarios where validation may take time.

  • ajv:

    AJV is known for its exceptional performance, making it one of the fastest JSON schema validators available. It compiles schemas into efficient JavaScript functions, which allows for rapid validation of large datasets, making it ideal for performance-critical applications.

  • joi:

    Joi is not as fast as AJV but offers a balance between performance and usability. It provides a rich set of validation features, which may introduce some overhead. However, for most applications, the performance is adequate and often overshadowed by its expressive API.

  • jsonschema:

    jsonschema is lightweight and performs well for basic validation tasks. However, it may not be as optimized for speed as AJV, making it more suitable for smaller projects or where performance is not the primary concern.

API Design

  • z-schema:

    z-schema provides a comprehensive API that supports various JSON Schema drafts. It is designed for flexibility and allows for custom validation functions, although it may require more boilerplate code compared to Joi.

  • ajv:

    AJV provides a minimalistic and straightforward API that allows developers to define schemas and validate data with ease. It supports custom keywords and asynchronous validation, making it flexible for various use cases.

  • joi:

    Joi has a very expressive and intuitive API that allows for complex validation rules to be defined in a readable manner. Its chaining syntax makes it easy to create intricate validation schemas, which can enhance developer productivity.

  • jsonschema:

    jsonschema offers a simple API that closely follows the JSON Schema specification. It is easy to use for basic validations but may lack some advanced features found in other libraries, making it less flexible for complex scenarios.

Extensibility

  • z-schema:

    z-schema supports extensibility through custom validation functions, allowing developers to implement specific validation logic. However, it may require more effort to set up compared to AJV and Joi.

  • ajv:

    AJV is highly extensible, allowing developers to create custom validation keywords and formats. This makes it suitable for applications that require specific validation rules beyond the standard JSON Schema definitions.

  • joi:

    Joi is also extensible and allows for custom validation methods. Its rich API enables developers to easily create reusable validation logic, making it a great choice for complex applications with unique validation needs.

  • jsonschema:

    jsonschema has limited extensibility compared to AJV and Joi. It adheres closely to the JSON Schema specification, which may restrict the ability to implement custom validation logic without additional work.

Learning Curve

  • z-schema:

    z-schema has a moderate learning curve. While it is not overly complex, its extensive feature set may require some time to fully understand and utilize effectively.

  • ajv:

    AJV has a relatively low learning curve, especially for developers familiar with JSON Schema. Its straightforward API and comprehensive documentation make it easy to get started with schema validation.

  • joi:

    Joi has a gentle learning curve due to its intuitive API design. Developers can quickly grasp how to define schemas and validation rules, making it accessible for newcomers to validation libraries.

  • jsonschema:

    jsonschema is easy to learn for those familiar with JSON Schema, but its lack of advanced features may limit its appeal for more complex validation needs. It is suitable for developers looking for a simple validation solution.

Community and Support

  • z-schema:

    z-schema has a moderate community presence, with decent documentation and support. While it may not be as widely adopted as AJV or Joi, it still offers sufficient resources for developers.

  • ajv:

    AJV has a robust community and is actively maintained, with frequent updates and a wealth of resources available for developers. This support can be invaluable when troubleshooting or seeking best practices.

  • joi:

    Joi is widely used in the Node.js community, which means there is a wealth of tutorials, examples, and community support available. Its popularity ensures that developers can find help easily.

  • jsonschema:

    jsonschema has a smaller community compared to AJV and Joi, which may result in fewer resources and examples. However, it is still a reliable choice for basic validation needs.

How to Choose: z-schema vs ajv vs joi vs jsonschema

  • z-schema:

    Consider z-schema if you need a JSON schema validator that supports draft-04 and draft-06 of JSON Schema, with additional features like asynchronous validation and a focus on performance. It's a good choice for applications requiring strict adherence to schema definitions.

  • ajv:

    Choose AJV if you need a high-performance JSON schema validator that supports the latest JSON Schema standards and offers features like asynchronous validation and custom keywords. It's particularly suitable for applications where speed is critical and you need to validate large datasets quickly.

  • joi:

    Select Joi if you prefer a more expressive and user-friendly API for schema validation, especially in Node.js applications. Joi allows for complex validation rules and is highly customizable, making it ideal for validating request payloads in APIs.

  • jsonschema:

    Opt for jsonschema if you are looking for a straightforward and lightweight library that adheres closely to the JSON Schema specification. It is suitable for projects that require basic validation without additional features or complexity.

README for z-schema

z-schema

Fast, lightweight JSON Schema validator for Node.js and browsers with full support for the latest JSON Schema draft (2020-12), plus draft-2019-09, draft-07, draft-06, and draft-04.

NPM

Coverage Status

Install

npm install z-schema

Requires Node.js 22 or later.

Quick Start

ESM / TypeScript

import ZSchema from 'z-schema';

const validator = ZSchema.create();

try {
  validator.validate({ name: 'Alice' }, { type: 'object', properties: { name: { type: 'string' } } });
  console.log('Valid');
} catch (error) {
  console.log('Invalid:', error.details);
}

CommonJS

const ZSchema = require('z-schema');
const validator = ZSchema.create();

Browser (UMD)

<script src="z-schema/umd/ZSchema.min.js"></script>
<script>
  const validator = ZSchema.create();
  try {
    validator.validate('hello', { type: 'string' });
  } catch (error) {
    console.log(error.details);
  }
</script>

CLI

npm install --global z-schema
z-schema mySchema.json
z-schema mySchema.json myData.json
z-schema --strictMode mySchema.json myData.json

Usage

ZSchema.create() returns one of four validator variants based on the async and safe options:

OptionsClassvalidate() returns
{}ZSchematrue (throws on error)
{ safe: true }ZSchemaSafe{ valid, err? }
{ async: true }ZSchemaAsyncPromise<true> (rejects)
{ async: true, safe: true }ZSchemaAsyncSafePromise<{ valid, err? }>

Sync Validation (Throw Mode)

By default, validate throws a ValidateError on failure. The error has a details array with structured error info.

const validator = ZSchema.create(); // returns ZSchema

try {
  validator.validate(json, schema); // returns true
} catch (error) {
  console.log(error.name); // 'z-schema validation error'
  console.log(error.message); // summary message
  console.log(error.details); // array of { code, message, path, ... }
}

Sync Validation (Safe Mode)

Use { safe: true } to get a ZSchemaSafe instance whose validate() returns a result object instead of throwing.

const validator = ZSchema.create({ safe: true }); // returns ZSchemaSafe

const result = validator.validate(json, schema); // { valid: boolean, err?: ValidateError }
if (!result.valid) {
  console.log(result.err!.details);
}

Async Validation (Throw Mode)

Pass { async: true } to support async format validators. Returns a ZSchemaAsync instance whose validate() returns a Promise.

const validator = ZSchema.create({ async: true }); // returns ZSchemaAsync

try {
  await validator.validate(json, schema); // Promise<true>
} catch (error) {
  console.log(error.details);
}

Async Validation (Safe Mode)

Combine both options to get a ZSchemaAsyncSafe instance — the promise always resolves (never rejects) with a result object.

const validator = ZSchema.create({ async: true, safe: true }); // returns ZSchemaAsyncSafe

const result = await validator.validate(json, schema); // Promise<{ valid, err? }>
if (!result.valid) {
  console.log(result.err!.details);
}

Schema Compilation

Pre-compile schemas at startup to validate $ref references and cache compiled schemas.

const validator = ZSchema.create();

const schemas = [
  { id: 'person', type: 'object', properties: { name: { type: 'string' } }, required: ['name'] },
  { id: 'team', type: 'object', properties: { lead: { $ref: 'person' } } },
];

try {
  validator.validateSchema(schemas);
} catch (error) {
  console.log('Schema errors:', error.details);
}

Custom Format Validators

Register custom format validators for sync or async checks.

const validator = ZSchema.create();

// Sync format
validator.registerFormat('uppercase', (value: unknown): boolean => {
  return typeof value === 'string' && value === value.toUpperCase();
});

// Async format
validator.registerFormat('user-exists', async (value: unknown): Promise<boolean> => {
  if (typeof value !== 'number') return false;
  const user = await db.getUserById(value);
  return user != null;
});

Remote References

If your schemas reference remote URIs, register them before validation.

const validator = ZSchema.create();

// Register a remote schema manually
validator.setRemoteReference('http://example.com/person.json', personSchema);

// Or set a schema reader to load them automatically
ZSchema.setSchemaReader((uri: string) => {
  const filePath = path.resolve(__dirname, 'schemas', uri + '.json');
  return JSON.parse(fs.readFileSync(filePath, 'utf8'));
});

Version History

VersionChanges
v12Default version is draft2020-12. Full support for draft-2020-12 and draft-2019-09.
v11Default version is draft-07. Implemented draft-07 tests from JSON Schema Test Suite.
v10Default version is draft-06. Implemented draft-06 tests from JSON Schema Test Suite.
v9New factory API: ZSchema.create() replaces new ZSchema(). New cache algorithms.
v8Schemas without $schema default to draft-04. Use { version: 'none' } for the old v7 behavior.
v7Rewritten in TypeScript/ESM. Passes all JSON Schema Test Suite tests for draft-04.
v6Legacy version. Draft-04 support.

Features

See docs/features.md for the full feature list.

Options

See docs/options.md for all constructor and per-call options.

Documentation

DocumentDescription
docs/usage.mdDetailed usage guide with all validation modes, error handling, and advanced features
docs/options.mdConstructor options and per-call validation options
docs/features.mdFeature catalog with examples
docs/MIGRATION.mdMigration guide for upgrading between major versions
docs/architecture.mdInternal architecture, module structure, and public API reference
docs/conventions.mdCode style, naming, and formatting conventions
docs/testing.mdTest framework, running tests, and writing new tests
docs/contributing.mdPR workflow and contribution guidelines

Contributing

This repository uses submodules. Clone with:

git clone --recursive https://github.com/zaggino/z-schema.git

See docs/contributing.md for the full contribution guide.

Contributors

Big thanks to:

sergey-shandar
Sergey Shandar
IvanGoncharov
Ivan Goncharov
pgonzal
Pete Gonzalez (OLD ALIAS)
simon-p-r
Simon R
TheToolbox
Jason Oettinger
whitlockjc
Jeremy Whitlock
epoberezkin
Evgeny
toofishes
Dan McGee
antialias
Thomas Hallock
kallaspriit
Priit Kallas
santam85
Marco Santarelli
Hirse
Jan Pilzer
geraintluff
Geraint
dgerber
Daniel Gerber
addaleax
Anna Henningsen
mctep
Konstantin Vasilev
barrtender
barrtender
RomanHotsiy
Roman Hotsiy
sauvainr
RenaudS
figadore
Reese
MattiSG
Matti Schneider
sandersky
Matthew Dahl
jfromaniello
José F. Romaniello
KEIII
Ivan Kasenkov
HanOterLin
Tony Lin
domoritz
Dominik Moritz
Semigradsky
Dmitry Semigradsky
countcain
Tao Huang
BuBuaBu
BuBuaBu

and to everyone submitting issues on GitHub