Validating JSON with ajv

A quick hello-world for the fastest JSON validator in the land.

Sooner or later, even with the most schemaless of architectures, you’re going to need to validate some JSON passed to you by a user. And when that time comes, you’ll want to use the fastest library out there. So today I learned about Ajv (Another JSON Schema Validator).

One of the cornerstones of the node ecosystem (it’s ajv that’s checking those webpack files!) ajv is a well maintained, active package that is demonstrably 50% faster than it’s closest competitor. It’s also strikingly simple to use- even if you do have to learn how to define a JSON schema.

Using ajv is fairly simple, although I did struggle to find a cut-and-dry example, so here’s a trivial one. First import the library and create a validator builder with the options you want:

In this case we’re only asking for a validator that returns all the errors (rather than just halting on the first). There’s a good variety of options in ajv, including the option to coerce types, and choose between quick or complete date-time validation.

Next you need the schema:

JSON Schema is an official thing. Albeit something that appears to be in a perpetual state of ‘draft’. So far ‘Understanding JSON Schema’ is the best resource I found for getting started. The above schema is for an object that only has a single property, hello, which is a string.

Finally we need to compile the schema against our validator to create a validation function, which can then be used to test against Javascript Objects (note that, ajv does not run JSON.parse() for you.)

The above code will return the object if it matches the schema (think const obj = { hello: 'world' } or a collection of machine readable, and human comprehensible errors if not.

From my experience, validation seems as quick as it says on the tin. The JSON Schema definitions are cumbersome, but have some powerful abstractions (including references and extensions). The errors are also structured enough for a machine to be able to parse and correct (if possible), or to easily coerce into something that the average end-user could understand.

So have fun, and stay valid- kids.

Like what you read? Give thomas michael wallace a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.