The fastest JSON schema validator for Node.js and browser.
Supports JSON Schema draft-06/07/2019-09 (draft-04 is supported in version 6) and JSON Type Definition RFC8927.
Ajv version 7 has these new features:
- NEW: support of JSON Type Definition RFC8927 (from v7.1.0), including generation of serializers and parsers from JTD schemas that are more efficient than native JSON serialization/parsing, combining JSON string parsing and validation in one function.
- support of JSON Schema draft-2019-09 features:
unevaluatedProperties
andunevaluatedItems
, dynamic recursive references and other additional keywords. - to reduce the mistakes in JSON schemas and unexpected validation results, strict mode is added - it prohibits ignored or ambiguous JSON Schema elements.
- to make code injection from untrusted schemas impossible, code generation is fully re-written to be safe and to allow code optimization (compiled schema code size is reduced by more than 10%).
- to simplify Ajv extensions, the new keyword API that is used by pre-defined keywords is available to user-defined keywords - it is much easier to define any keywords now, especially with subschemas. ajv-keywords package was updated to use the new API (in v4.0.0)
- schemas are compiled to ES6 code (ES5 code generation is also supported with an option).
- to improve reliability and maintainability the code is migrated to TypeScript.
Please note:
- the support for JSON-Schema draft-04 is removed - if you have schemas using "id" attributes you have to replace them with "$id" (or continue using Ajv v6 that will be supported until 02/28/2021).
- all formats are separated to ajv-formats package - they have to be explicitly added if you use them.
See release notes for the details.
To install the new version:
npm install ajv
See Getting started for code example.
100+ people contributed to Ajv. You are very welcome to join by implementing new features that are valuable to many users and by improving documentation.
Please do not be disappointed if your suggestion is not accepted - it is important to maintain the balance between the library size, performance and functionality. If it seems that a feature would benefit only a small number of users, its addition may be delayed until there is more support from the users community - so please submit the issue first to explain why this feature is important.
Please include documentation and test coverage with any new feature implementations.
To run tests:
npm install
git submodule update --init
npm test
npm run build
- compiles typescript to dist
folder.
Please review Contributing guidelines and Code components.
- Platinum sponsors
- Using version 7
- Contributing
- Mozilla MOSS grant and OpenJS Foundation
- Sponsors
- Performance
- Features
- Getting started
- Choosing schema language
- Frequently Asked Questions
- Using in browser
- Using in ES5 environment
- Command line interface
- API reference
- NEW: Strict mode
- Data validation
- Extending Ajv
- User-defined keywords:
- Plugins
- Related packages
- Security considerations
- Some packages using Ajv
- Changes history
- Support, Code of conduct, Contacts, License
Ajv has been awarded a grant from Mozilla’s Open Source Support (MOSS) program in the “Foundational Technology” track! It will sponsor the development of Ajv support of JSON Schema version 2019-09 and of JSON Type Definition (RFC8927).
Ajv also joined OpenJS Foundation – having this support will help ensure the longevity and stability of Ajv for all its users.
This blog post has more details.
I am looking for the long term maintainers of Ajv – working with ReadySet, also sponsored by Mozilla, to establish clear guidelines for the role of a "maintainer" and the contribution standards, and to encourage a wider, more inclusive, contribution from the community.
Please sponsor Ajv development
Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant!
Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released.
Please sponsor Ajv via:
- GitHub sponsors page (GitHub will match it)
- Ajv Open Collective️
Thank you.
Ajv generates code to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization.
Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks:
- json-schema-benchmark - 50% faster than the second place
- jsck benchmark - 20-190% faster
- z-schema benchmark
- themis benchmark
Performance of different validators by json-schema-benchmark:
- Ajv implements JSON Schema draft-06/07/2019-09 standards (draft-04 is supported in v6):
- all validation keywords (see JSON Schema validation keywords)
- keyword "nullable" from Open API 3 specification.
- full support of remote references (remote schemas have to be added with
addSchema
or compiled to be available) - support of circular references between schemas
- correct string lengths for strings with unicode pairs
- formats defined by JSON Schema draft-07 standard (with ajv-formats plugin) and additional formats (can be turned off)
- validates schemas against meta-schema
- NEW: supports JSON Type Definition:
- all forms (see JSON Type Definition schema forms)
- meta-schema for JTD schemas
- "union" keyword and user-defined keywords (can be used inside "metadata" member of the schema)
- supports browsers and Node.js 0.10-14.x
- asynchronous loading of referenced schemas during compilation
- "All errors" validation mode with option allErrors
- error messages with parameters describing error reasons to allow error message generation
- i18n error messages support with ajv-i18n package
- removing-additional-properties
- assigning defaults to missing properties and items
- coercing data to the types specified in
type
keywords - user-defined keywords
- draft-06/07 keywords
const
,contains
,propertyNames
andif/then/else
- draft-06 boolean schemas (
true
/false
as a schema to always pass/fail). - additional extension keywords with ajv-keywords package
- $data reference to use values from the validated data as values for the schema keywords
- asynchronous validation of user-defined formats and keywords
To install version 7:
npm install ajv
Try it in the Node.js REPL: https://runkit.com/npm/ajv
In JavaScript:
// or ESM/TypeScript import
import Ajv from "ajv"
// Node.js require:
const Ajv = require("ajv").default
const ajv = new Ajv() // options can be passed, e.g. {allErrors: true}
const validate = ajv.compile(schema)
const valid = validate(data)
if (!valid) console.log(validate.errors)
In TypeScript:
import Ajv, {JSONSchemaType, DefinedError} from "ajv"
const ajv = new Ajv()
type MyData = {foo: number}
// Optional schema type annotation for schema to match MyData type.
// To use JSONSchemaType set `strictNullChecks: true` in tsconfig `compilerOptions`.
const schema: JSONSchemaType<MyData> = {
type: "object",
properties: {
foo: {type: "number", minimum: 0},
},
required: ["foo"],
additionalProperties: false,
}
// validate is a type guard for MyData - type is inferred from schema type
const validate = ajv.compile(schema)
// or, if you did not use type annotation for the schema,
// type parameter can be used to make it type guard:
// const validate = ajv.compile<MyData>(schema)
const data: any = {foo: 1}
if (validate(data)) {
// data is MyData here
console.log(data.foo)
} else {
// The type cast is needed to allow user-defined keywords and errors
// You can extend this type to include your error types as needed.
for (const err of validate.errors as DefinedError[]) {
switch (err.keyword) {
case "minimum":
// err type is narrowed here to have "minimum" error params properties
console.log(err.params.limit)
break
// ...
}
}
}
With JSON Type Definition schema:
In JavaScript:
const Ajv = require("ajv").default
const ajv = new Ajv() // options can be passed, e.g. {allErrors: true}
const schema = {
properties: {
foo: {type: "float64"},
},
}
const validate = ajv.compile(schema)
const valid = validate({foo: 1}) // true
if (!valid) console.log(validate.errors)
// Unlike JSON Schema:
const valid1 = validate(1) // false, bot an object
const valid2 = validate({}) // false, foo is required
const valid3 = validate({foo: 1, bar: 2}) // false, bar is additional
In TypeScript:
import {JTDSchemaType} from "ajv"
type MyData = {foo: number}
// Optional schema type annotation for schema to match MyData type.
// To use JTDSchemaType set `strictNullChecks: true` in tsconfig `compilerOptions`.
const schema: JTDSchemaType<MyData> = {
properties: {
foo: {type: "float64"},
},
}
See this test for an advanced example, API reference and Options for more details.
Ajv compiles schemas to functions and caches them in all cases (using schema itself as a key for Map) or another function passed via options), so that the next time the same schema is used (not necessarily the same object instance) it won't be compiled again.
The best performance is achieved when using compiled functions returned by compile
or getSchema
methods (there is no additional function call).
Please note: every time a validation function or ajv.validate
are called errors
property is overwritten. You need to copy errors
array reference to another variable if you want to use it later (e.g., in the callback). See Validation errors
See Content Security Policy to decide the best approach how to use Ajv in the browser.
Whether you use Ajv or compiled schemas, it is recommended that you bundle them together with your code.
If you need to use Ajv in several bundles you can create a separate UMD bundles using npm run bundle
script.
Then you need to load Ajv with support of JSON Schema draft-07 in the browser:
<script src="bundle/ajv7.min.js"></script>
<script>
;(function () {
const Ajv = window.ajv7.default
const ajv = new Ajv()
})()
</script>
To load the bundle that supports JSON Schema draft-2019-09:
<script src="bundle/ajv2019.min.js"></script>
<script>
;(function () {
const Ajv = window.ajv2019.default
const ajv = new Ajv()
})()
</script>
To load the bundle that supports JSON Type Definition:
<script src="bundle/ajvJTD.min.js"></script>
<script>
;(function () {
const Ajv = window.ajvJTD.default
const ajv = new Ajv()
})()
</script>
This bundle can be used with different module systems; it creates global ajv
(or ajv2019
) if no module system is found.
The browser bundle is available on cdnjs.
Please note: some frameworks, e.g. Dojo, may redefine global require in a way that is not compatible with CommonJS module format. In this case Ajv bundle has to be loaded before the framework and then you can use global ajv
(see issue #234).
Both JSON Schema and JSON Type Definition are cross-platform specifications with implementations in multiple programming languages that help you define the shape and requirements to your JSON data.
This section compares their pros/cons to help decide which specification fits your application better.
- Pros
- Wide specification adoption.
- Used as part of OpenAPI specification.
- Support of complex validation scenarios:
- untagged unions and boolean logic
- conditional schemas and dependencies
- restrictions on the number ranges and the size of strings, arrays and objects
- semantic validation with formats, patterns and content keywords
- distribute strict record definitions across multiple schemas (with unevaluatedProperties)
- Can be effectively used for validation of any JavaScript objects and configuration files.
- Cons
- Defines the collection of restrictions on the data, rather than the shape of the data.
- No standard support for tagged unions.
- Complex and error prone for the new users (Ajv has strict mode to compensate for it, but it is not cross-platform).
- Some parts of specification are difficult to implement, creating the risk of implementations divergence:
- reference resolution model
- unevaluatedProperties/unevaluatedItems
- dynamic recursive references
- Internet draft status (rather than RFC)
See JSON Schema for the list of defined keywords.
- Pros:
- Aligned with type systems of many languages - can be used to generate type definitions and efficient parsers and serializers to/from these types.
- Very simple, enforcing the best practices for cross-platform JSON API modelling.
- Simple to implement, ensuring consistency across implementations.
- Defines the shape of JSON data via strictly defined schema forms (rather than the collection of restrictions).
- Effective support for tagged unions.
- Designed to protect against user mistakes.
- Approved as RFC8927
- Cons:
- Limited, compared with JSON Schema - no support for untagged unions*, conditionals, references between different schema files**, etc.
- No meta-schema in the specification*.
- Brand new - limited industry adoption (as of January 2021).
* Ajv defines meta-schema for JTD schemas and non-standard keyword "union" that can be used inside "metadata" object.
** You can still combine schemas from multiple files in the application code.
See JSON Type Definition for the list of defined schema forms.
You need to:
- recompile Typescript to ES5 target - it is set to 2018 in the bundled compiled code.
- generate ES5 validation code:
const ajv = new Ajv({code: {es5: true}})
See Advanced options.
CLI is available as a separate npm package ajv-cli. It supports:
- compiling JSON Schemas to test their validity
- generating standalone validation code that exports validation function(s) to be used without Ajv
- migrating schemas to draft-07 and draft-2019-09 (using json-schema-migrate)
- validating data file(s) against JSON Schema
- testing expected validity of data against JSON Schema
- referenced schemas
- user-defined meta-schemas, validation keywords and formats
- files in JSON, JSON5, YAML, and JavaScript format
- all Ajv options
- reporting changes in data after validation in JSON-patch format
See section in data validation and the detailed guide.
Ajv can be extended with plugins that add keywords, formats or functions to process generated code. When such plugin is published as npm package it is recommended that it follows these conventions:
- it exports a function that accepts ajv instance as the first parameter - it allows using plugins with ajv-cli.
- this function returns the same instance to allow chaining.
- this function can accept an optional configuration as the second parameter.
You can import Plugin
interface from ajv if you use Typescript.
If you have published a useful plugin please submit a PR to add it to the next section.
- ajv-bsontype - plugin to validate mongodb's bsonType formats
- ajv-cli - command line interface
- ajv-formats - formats defined in JSON Schema specification
- ajv-errors - plugin for defining error messages in the schema
- ajv-i18n - internationalised error messages
- ajv-istanbul - plugin to instrument generated validation code to measure test coverage of your schemas
- ajv-keywords - plugin with additional validation keywords (select, typeof, etc.)
- ajv-merge-patch - plugin with keywords $merge and $patch
- ajv-formats-draft2019 - format validators for draft2019 that aren't included in ajv-formats (ie.
idn-hostname
,idn-email
,iri
,iri-reference
andduration
)
- webpack - a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser
- jsonscript-js - the interpreter for JSONScript - scripted processing of existing endpoints and services
- osprey-method-handler - Express middleware for validating requests and responses based on a RAML method object, used in osprey - validating API proxy generated from a RAML definition
- har-validator - HTTP Archive (HAR) validator
- jsoneditor - a web-based tool to view, edit, format, and validate JSON http://jsoneditoronline.org
- JSON Schema Lint - a web tool to validate JSON/YAML document against a single JSON Schema http://jsonschemalint.com
- objection - SQL-friendly ORM for Node.js
- table - formats data into a string table
- ripple-lib - a JavaScript API for interacting with Ripple in Node.js and the browser
- restbase - distributed storage with REST API & dispatcher for backend services built to provide a low-latency & high-throughput API for Wikipedia / Wikimedia content
- hippie-swagger - Hippie wrapper that provides end to end API testing with swagger validation
- react-form-controlled - React controlled form components with validation
- rabbitmq-schema - a schema definition module for RabbitMQ graphs and messages
- @query/schema - stream filtering with a URI-safe query syntax parsing to JSON Schema
- chai-ajv-json-schema - chai plugin to us JSON Schema with expect in mocha tests
- grunt-jsonschema-ajv - Grunt plugin for validating files against JSON Schema
- extract-text-webpack-plugin - extract text from bundle into a file
- electron-builder - a solution to package and build a ready for distribution Electron app
- addons-linter - Mozilla Add-ons Linter
- gh-pages-generator - multi-page site generator converting markdown files to GitHub pages
- ESLint - the pluggable linting utility for JavaScript and JSX
- Spectral - the customizable linting utility for JSON/YAML, OpenAPI, AsyncAPI, and JSON Schema
See https://github.com/ajv-validator/ajv/releases
Please note: Changes in version 7.0.0
Please review and follow the Code of conduct.
Please report any unacceptable behaviour to ajv.validator@gmail.com - it will be reviewed by the project team.
To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues.
Ajv is a part of Tidelift subscription - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers.