JSON Schema Overview and Examples

JSON Schema is a tool to define and validate the structure of JSON data. It ensures that the data adheres to specific types, structures, and constraints, making it useful for APIs and data validation.

Basic JSON Schema Example

This schema defines a “Person” object with properties `name`, `age`, and `email`.

1
2
3
4
5
6
7
8
9
10
11
{
  "title": "Person",
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "integer", "minimum": 0 },
    "email": { "type": "string", "format": "email" }
  },
  "required": ["name", "email"]
}

Explanation:

Valid Example for this Schema:

1
2
3
4
5
{
  "name": "John Doe",
  "age": 28,
  "email": "john@example.com"
}

Arrays in JSON Schema

You can validate arrays by specifying the type of items and enforcing constraints like minItems or uniqueItems.

Array Schema Example

1
2
3
4
5
6
{
  "type": "array",
  "items": { "type": "string" },
  "minItems": 1,
  "uniqueItems": true
}

This schema defines an array where:

Valid JSON Array:

1
2
3
4
5
[
  "apple",
  "banana",
  "cherry"
]

Conditional Validation in JSON Schema

JSON Schema supports conditional logic using if, then, and else.

Schema for Conditional Validation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
  "type": "object",
  "properties": {
    "isEmployed": { "type": "boolean" }
  },
  "if": {
    "properties": { "isEmployed": { "const": true } }
  },
  "then": {
    "properties": {
      "employer": { "type": "string" }
    },
    "required": ["employer"]
  },
  "else": {
    "properties": {
      "reasonUnemployed": { "type": "string" }
    },
    "required": ["reasonUnemployed"]
  }
}

Explanation:

Valid Example (Employed):

1
2
3
4
{
  "isEmployed": true,
  "employer": "TechCorp"
}

Valid Example (Unemployed):

1
2
3
4
{
  "isEmployed": false,
  "reasonUnemployed": "Student"
}

Summary

JSON Schema is versatile for defining the structure and validation rules for JSON data. It supports basic types, complex structures like arrays, and conditional logic, allowing developers to ensure data consistency and correctness. By using JSON Schema, you can make sure your data adheres to predefined formats, helping with integration and error prevention in APIs and applications.