Validating data is an important process. It helps to ensure that applications operate smoothly. One powerful tool for this purpose is the JSON Schema Validator.

In this post, I will introduce you to the fundamentals of using JSON Schema to validate your data, helping you ensure your JSON data structure follows the specified requirements.

What is JSON Schema?

JSON Schema is a declarative language for defining structure and constraints for JSON data.

JSON Schema will also be considered as a design document for input data as it is declared to define the rules, structure and constraints for input data.

What is JSON Schema Validator?

JSON Schema Validators are tools that implement the JSON Schema specification.

JSON schema validator help to check whether the input JSON data complies with the rules and structure defined in the created JSON Schema.

Try it out!

Step 1: Create a JSON Schema

To understand how to define a JSON schema, refer to the link bellow

 https://json-schema.org/understanding-json-schema/reference

In this post, I will create a simple JSON Schema for employee information as bellow

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "title": "Employee Schema",
    "type": "object",  
    "additionalProperties": false,
    "properties": {
      "name": {
        "type": "string",
        "description": "Full name of the employee"
      },
      "dateOfBirth": {
        "type": "string",
        "format": "date"
      },
      "age": {
        "type": "integer",
        "minimum": 18,
        "maximum": 65,
        "description": "Age of the employee, must be between 18 and 65"
      },
      "employee_id": {
        "type": "string",
        "pattern": "^[A-Z]{2}[0-9]{4}$",
        "description": "Employee ID in the format of two uppercase letters followed by four digits"
      },
      "department": {
        "type": "string",
        "enum": [ "HR", "Engineering", "Sales", "Marketing", "Finance"],
        "description": "Department the employee belongs to"
      },
      "email": {
        "type": "string",
        "format": "email",
        "description": "Employee's email address"
      },
      "country": {
        "type": "string",
        "const": "VietNam",
        "description": "Employee's country",
        "$comment": "Only for Vietnamese employees"
      }
    },
    "required": ["name", "age", "employee_id", "department", "email", "country", "dateOfBirth"
    ]
  }

 

Step 2: Prepare JSON Data

Prepare your JSON Instance with valid data (valid_data.json)

{
  "name": "Nguyen Van An",
  "dateOfBirth": "1994-01-15",
  "age": 30,
  "employee_id": "SL0221",
  "department": "Sales",
  "email": "annv@compa.com",
  "country": "VietNam"
}

 

Step 3: Install Ajv JSON schema validator

Ajv is used by a large number of JavaScript applications and libraries in all JavaScript environments - Node.js, browser, Electron apps, WeChat mini-apps etc. It allows implementing complex data validation logic via declarative schemas for your JSON data, without writing code.

Install AJV JSON schema validator using npm

npm install ajv  

 

Step 4: Validate JSON Data with Javascript

Now, try it with JavaScript (validate.js)      

const Ajv = require("ajv");
const ajv = new Ajv();

// Define date format
ajv.addFormat("date", { type:"string", validate: (dateString) =>{ return /^\d{4}-\d{2}-\d{2}$/.test(dateString) && !isNaN(new Date(dateString).getTime()); } });

// Define email format
ajv.addFormat("email", { type:"string", validate: (email) => { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailRegex.test(email); } });

// Load JSON Schema
const schema = require("../schema.json");

// Load JSON Data
const data = require("../valid_data.json");

// Compile schema
const validate = ajv.compile(schema);

// Validate data
const valid = validate(data);

if (valid) {
  console.log("★★★ JSON data is valid! ★★★");
} else {
  console.log("-+-+ JSON data is invalid +-+-");
  //for display the validate.errors
  //console.log("JSON data is invalid:", validate.errors);
}

 

Directory structure

src/
├─ validate.js
valid_data.json
schema.json

 

Execute the javascript source code to validate the valid_data.json

Validation Result is valid data with valid_data.json


Now, I try to create an invalid_data.json with invalid data

{
  "name": "Nguyen Van An",
  "age": 14,
  "employee_id": "SL0221",
  "department": "Sales",
  "email": "annvcompa.com",
  "country": "Japan",
  "dateOfBirth": "2010-11"
}

 

Load it with javascript

// Load JSON Data
//const data = require("../valid_data.json");
const data = require("../invalid_data.json");

 

Directory structure

src/
├─ validate.js
valid_data.json
schema.json
invalid_data.json

 

Execute validate.js file

Validation Result is invalid data with invalid_data.json

To check error details, use the website https://www.jsonschemavalidator.net/

 

When to use a JSON Schema validator?

If you need to validate JSON data in your application, JSON Schema provides a standardized way to check the structure and content of the data. This is especially useful for ensuring data integrity and consistency.

 

Conclusion

By defining clear rules and constraints, JSON Schema not only minimizes errors but also enhances reliability and consistency in your applications.

JSON Schema validator helps you ensure that JSON data is structured and validated correctly.

Take the time to research and implement JSON Schema validator in your projects. You'll find that managing and validating data becomes easier and more efficient than ever before.

 

References

https://json-schema.org/overview/what-is-jsonschema

https://ajv.js.org

https://www.jsonschemavalidator.net

https://json-schema.org/understanding-json-schema/reference

https://json-schema.org/img/json_schema.svg

https://hailbytes.com/wp-content/uploads/2022/02/JSON_SchemaTitle_Image.png