JavaScript JSON Schema validation

In this tutorial we are going to learn how to validate objects against a JSON schema, using JavaScript.

Introduction

In this tutorial we are going to learn how to validate objects against a JSON schema, using JavaScript. We will be using the ajv library.

To install this library using NPM, we simply need to send the following command:

npm install ajv

If you need help creating a JSON schema that validates a given JSON object, you can use this online tool.

The code

We will start our code by importing the Ajv constructor function.

const Ajv = require('ajv');

Then we will define a variable with a JSON schema representing a person object that has the following required properties:

  • name (a string);
  • age (an integer);
  • married (a boolean).
const schema = `{
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "age": {
      "type": "integer"
    },
    "married": {
      "type": "boolean"
    }
  },
  "required": [
    "name",
    "age",
    "married"
  ]
}`;

So, for an object to be valid accordingly to the previous schema, it needs to contain the 3 properties mentioned and the data types also need to be the ones defined.

Note that we have declared our JSON schema as a string, but we need to pass it as an object to the Ajv functions we are going to use below. Taking this in consideration, we are going to parse this string to an object and store it in a variable, to use it later. For a tutorial on how to parse JSON with JavaScript, please check here.

const schemaAsObject = JSON.parse(schema);

After this, we are going to define a JavaScript object that conforms with our JSON schema. So, as already mentioned, it needs to have the 3 required properties and the correct data types for each one of those.

const validObj = {
    name: "Ted",
    age: 20,
    married: true
};

We are also going to define another JavaScript object, this time not conforming with our JSON schema. It will have the name property missing and the age will be defined as a string (wrong data type).

const invalidObj = {
    age: "20",
    married: true
};

After this we are going to create an Ajv validator instance. As input of the constructor, we can pass an object with some configurations. For exemplification purposes, we are going to set the allErrors configuration to true, which sets the validator to verify all the errors. By default, this property is set to false, which means the validation stops after the first error is found. You can check here the full list of available configurations.

const ajv = new Ajv({allErrors: true});

After this we will call the validate method on our Ajv object, passing as first input the JSON schema and as second input the object we want to validate. As output, this method returns a Boolean indicating if the object is valid or not, considering the schema.

If validation errors are found, they can be obtained from the errors property of the Ajv instance. If no errors are found, the mentioned property will be set to null.

We will start by validating the valid object and printing the result to the console. We will also print the errors property, to confirm it is set to null.

console.log(ajv.validate(schemaAsObject, validObj));
console.log(ajv.errors);

We will then repeat the same but for the invalid object. In this case, we expect the errors property to contain the two errors.

console.log(ajv.validate(schemaAsObject, invalidObj));
console.log(ajv.errors);

The complete code can be seen below.

const Ajv = require('ajv');

const schema = `{
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "age": {
      "type": "integer"
    },
    "married": {
      "type": "boolean"
    }
  },
  "required": [
    "name",
    "age",
    "married"
  ]
}`;

const schemaAsObject = JSON.parse(schema);

const validObj = {
    name: "Ted",
    age: 20,
    married: true
};

const invalidObj = {
    age: "20",
    married: true
};

const ajv = new Ajv({allErrors: true});

console.log(ajv.validate(schemaAsObject, validObj));
console.log(ajv.errors);

console.log(ajv.validate(schemaAsObject, invalidObj));
console.log(ajv.errors);

Testing the code

To test the code, simply run it in a tool of your choice. In my case I’m using Visual Studio Code with the Code Runner extension.

As output, you should get a result similar to figure 1. As can be seen, when testing the first object, we get the Boolean value true, indicating it conforms with the schema. Consequently, the errors property is set to null, as expected.

For the second object, we get the Boolean value false, which indicates it was not valid accordingly to the schema. Then, we also get an array with two errors. As the messages explain, we are missing a required property called name and we have the wrong type for the age property, also as expected.

Output of the program, showing the result of the validations.
Figure 1 – Output of the program, showing the result of the validations.

Leave a Reply

%d bloggers like this: