But ... what is JSON Schema?

Have you ever wondered how in node.js, package.json and package-lock.json file's structure is predefined and prompts a description whenever we hover over a key ... also it has a set of predefined keys and values.

Well, that's because of ... drum roll please🥁🥁... JSON Schema.

So what is JSON Schema?

Well, JSON Schemas are like blueprints for your JSON data. They define the expected structure, data types, and validation rules. Think of them as the rules that your JSON data must follow in order to be considered valid. This is particularly valuable when dealing with APIs, configuration files, or any scenario where structured data integrity is critical.

Why Use JSON Schemas?

  1. Data Validation: JSON Schemas ensure that the data you receive or generate follows a predefined structure, reducing errors and inconsistencies.

  2. Documentation: Schemas act as documentation. Developers can quickly understand what each field means and its expected format.

  3. Collaboration: When working in teams, JSON Schemas serve as a contract, making sure everyone is on the same page regarding data format and rules.

  4. Error Handling: Schemas can help you catch data inconsistencies early, leading to more informative error messages.


So let's take an example to learn about its key components and features...

{
    "name":"Tony Stark",
    "email":"evendeadiamthehero@gmail.com",
    "age":"28"
}

Here we are creating a user profile having 3 key: value pairs. Each one has some specification and validation attached to it like the email must contain an @ or the age must be more than 18.

Here's how we can achieve that,

For name property,

 "name" : {
    "type": "string",
    "description": "name of the person"
}

Similarly for email, we can add validation for the email format,

"email" : {
    "type": "string",
    "format": "email",
    "description" : "email of the person"
}

So, the whole schema would look something like this

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {
        "name": {
            "type":"string",
            "description": "name of the person"
        },
        "email" : {
            "type": "string",
            "format": "email",
            "description" : "email of the person"
        },
        "age" : {
            "type": "number",
            "description":"age of the person",
            "minimum" : 18
        }
    }

}

NOTE :

  • mentioning the $schema at the top is used to specify the version of JSON Schema that the schema document adheres to. It provides a way to indicate which version of the JSON Schema specification is being used to define the structure and validation rules for the JSON data.

  • There are many more components that can be used like arrays, booleans (type definitions), maximum, enum , patterns etc (constraints).

How to Implement JSON Schemas:

  1. Create a Schema: Write a JSON document that outlines the structure and validation rules.

  2. Link Schemas: Reference the schema in your JSON data using the "$schema" keyword.

  3. Validation Tools: Leverage tools like AJV, a JSON Schema validator for JavaScript, to validate your JSON data against the schema.

    Example :

app.post('/create-user', (req, res) => {
  const isValid = ajv.validate(userSchema, req.body); // Validate against the schema
  if (!isValid) {
    return res.status(400).json({ error: 'Invalid data format' });
  }
  // Process the valid user data ...
  res.status(201).json({ message: 'User profile created successfully' });
});

For more information: https://json-schema.org/