How to Validate JSON Schema ?

Validating JSON schema ensures that the structure and data types within a JSON document adhere to a predefined schema. This process is crucial for ensuring data consistency and integrity in applications where JSON data is exchanged.

Approach

  • Import the Ajv Library, a popular JSON Schema validator for JavaScript.
  • A JSON schema is defined with specific properties and their corresponding types. Additionally, required fields are specified. Then, sample data is created adhering to the defined schema.
  • Initializing Ajv, An instance of Ajv is initialized, allowing us to use its functionalities.
  • The defined schema is compiled using Ajv’s “compile()” method, resulting in a validation function.
  • The compiled schema validation function is used to validate the sample data. If the data conforms to the schema, a success message is logged; otherwise, validation errors are logged.

Steps to Create Application

Initialize npm in your project directory.

npm init -y

Install the Ajv library using npm.

npm install ajv

Project structure:

Example: The example below shows how to Validate JSON Schema.

JavaScript
const Ajv = require("ajv");

// Define schema and data
const schema = {
    type: "object",
    properties: {
        name: { type: "string" },
        age: { type: "number" }
    },
    required: ["name", "age"]
};

const data = {
    name: "John Doe",
    age: 30
};

// Initialize Ajv
const ajv = new Ajv();

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

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

if (isValid) {
    console.log("Validation successful");
} else {
    console.log("Validation failed:", validate.errors);
}

Run the JavaScript file using Node.js.

node validate.js

Output:

validation successful

Contact Us