JSON Schema (https://json-schema.org/)

Defining a JSON Schema

The following is a simple JSON Object representing a product catalog:

{
    "id": 1,
    "name": "Lampshade",
    "price": 0
}

We could define its JSON Schema as follow:

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "Product",
    "description": "A product from the catalog",
    "type": "object",
    "properties": {
        "id": {
            "description": "The unique identifier for a product",
            "type": "integer"
        },
        "name": {
            "description": "Name of the product",
            "type": "string"
        },
        "price": {
            "type": "number",
            "minimum": 0,
            "exclusiveMinimum": true
        }
    },
    "required": ["id", "name", "price"]
}

As we can see a JSON Schema is a JSON document, and that document MUST be an object. Object members (or properties) defined by JSON Schema are called keywords.

Let’s explain the keywords that we have used in our sample:

  • The $schema keyword states that this schema is written according to the draft v4 specification.
  • The title and description keywords are descriptive only, in that they do not add constraints to the data being validated. The intent of the schema is stated with these two keywords: describes a product.
  • The type keyword defines the first constraint on our JSON data: it has to be a JSON Object.

Also, a JSON Schema MAY contain properties that are not schema keywords. In our case idnameprice will be members (or properties) of the JSON Object.

For each property, we can define the type. We defined id and name as string and price as number. In JSON Schema a number can have a minimum. By default this minimum is inclusive, so we need to specify exclusiveMinimum.

Finally, the Schema tells that idname, and price are required.

Resources