Skip to content

potlitel/JsonSchemaValidationsSamples

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 

Repository files navigation

JSON Schema - Validations samples

Table of Contents:

✨About

JSON Schema is a declarative language for annotating and validating JSON documents' structure, constraints, and data types. It provides a way to standardize and define expectations for JSON data.

Note

The JSON Schema team recommends using draft 7 or later. The current version is 2020-12! The previous version was 2019-09.

All the examples listed below have the same structure but for the sake of brevity, we will only be showing the code snippet corresponding to the validation segment:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://example.com/product.schema.json",
  "title": "Your title",
  "description": "Your description",
  "type": "object",
  "additionalProperties": false,
  "required": [ ... ],
  "properties": {
    "prop1": {
    },
    "prop2": {
    },
    "prop3": {
    },
    "propn": {
    }
  },
  "definitions": {
    "definition-1": {
    },
    "definition-2": {
    },
    "definition-n": {
    }
}

📃Validations samples

💠Required string prop

{
...// MORE CODE OMITTED FOR BREVITY
"required": [ "FirstName" ],
"properties": {
"FirstName": {
      "type": "string"
    },
},
...// MORE CODE OMITTED FOR BREVITY
}

💠Required string prop with pattern

{
...// MORE CODE OMITTED FOR BREVITY
"required": [ "telephone_number" ],
"properties": {
        "telephone_number": {
            "type": "string",
            "pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$" //"555-1212", "(888)555-1212", "(888)555-1212 ext. 532"
            },
},
...// MORE CODE OMITTED FOR BREVITY
}

💠boolean

{
...// MORE CODE OMITTED FOR BREVITY
"properties": {
        "ignitionStatus": {
          "type": "boolean",
          "description": "Property. Model:'https://schema.org/Boolean'. Gives the ignition status of the vehicle. True means ignited"
        },
},
...// MORE CODE OMITTED FOR BREVITY
}

💠minLength-maxLength

{
  ... // MORE CODE OMITTED FOR BREVITY
"familyName": {
      "type": "string",
      "minLength": 1,
      "maxLength": 256
    }
... // MORE CODE OMITTED FOR BREVITY
}

💠number

{
  ... // MORE CODE OMITTED FOR BREVITY
"cargoWeight": {
          "type": "number",
          "description": "Property. Current weight of the vehicle's cargo. Model:'https://schema.org/Number'. Units:'Kilograms'",
          "minimum": 0,
          "exclusiveMinimum": true
        },
... // MORE CODE OMITTED FOR BREVITY
}

💠minimum-maximum

{
  ... // MORE CODE OMITTED FOR BREVITY
"height": {
      "type": "number",
      "format": "double",
      "minimum": 0.0,
      "maximum": 3.0
    }
... // MORE CODE OMITTED FOR BREVITY
}

💠date

{
  ... // MORE CODE OMITTED FOR BREVITY
"dateVehicleFirstRegistered": {
          "type": "string",
          "format": "date",
          "description": "Property. The date of the first registration of the vehicle with the respective public authorities. Model:'https://schema.org/dateVehicleFirstRegistered'"
        },
... // MORE CODE OMITTED FOR BREVITY
}

💠date-time

{
  ... // MORE CODE OMITTED FOR BREVITY
"purchaseDate": {
          "type": "string",
          "format": "date-time",
          "description": "Property. The date the item e.g. vehicle was purchased by the current owner. Model:'https://schema.org/purchaseDate'"
        },
... // MORE CODE OMITTED FOR BREVITY
}

💠arrays

{
  ... // MORE CODE OMITTED FOR BREVITY
"tags": {
      "description": "Tags for the blog",
      "type": "array",
      "items": {
         "type": "string"
       },
       "minItems": 1,   
       "uniqueItems": true
    }
... // MORE CODE OMITTED FOR BREVITY
}

💠arrays-prefixItems

Tuple validation is useful when the array is a collection of items where each has a different schema and the ordinal index of each item is meaningful.

For example, you may represent a street address such as 1600 Pennsylvania Avenue NW as a 4-tuple of the form:

[number, street_name, street_type, direction]

Each of these fields will have a different schema:

  • number: The address number. Must be a number.
  • street_name: The name of the street. Must be a string.
  • street_type: The type of street. Should be a string from a fixed set of values.
  • direction: The city quadrant of the address. Should be a string from a different set of values.

The prefixItems keyword is an array, where each item is a schema that corresponds to each index of the document's array. That is, an array where the first element validates the first element of the input array, the second element validates the second element of the input array, etc.

{
  ... // MORE CODE OMITTED FOR BREVITY
"street_address": {
      "description": "street address as a 4-tuple",
      "type": "array",
      "prefixItems": [
            { "type": "number" },
            { "type": "string" },
            { "enum": ["Street", "Avenue", "Boulevard"] },
            { "enum": ["NW", "NE", "SW", "SE"] }
        ]
    }
... // MORE CODE OMITTED FOR BREVITY
}

Example

[1600, "Pennsylvania", "Avenue", "NW"]

💠defs

Sometimes we have small subschemas that are only intended for use in the current schema and it doesn't make sense to define them as separate schemas. The $defs keyword gives us a standardized place to keep subschemas intended for reuse in the current schema document.

{
  ... // MORE CODE OMITTED FOR BREVITY
"properties": {
        "primaryName": { "$ref": "#/$defs/personName" }
    },
... // MORE CODE OMITTED FOR BREVITY
"$defs": {
        "personName": {
            "type": "object",
            "properties": {
                "firstName": { "type": "string" },
                "lastName": { "type": "string" }
            },
            "additionalProperties": false
        }
}

Another usage

{
  ... // MORE CODE OMITTED FOR BREVITY
"properties": {
        "address": { "$ref": "#/$defs/address" }
    },
... // MORE CODE OMITTED FOR BREVITY
"$defs": {
        "address": {
            "type": "object",
            "properties": {
                "line1": { "type": "string" },
                "line2": { "type": "string" },
                "line3": { "type": "string" },
                "line4": { "type": "string" },
                "postalCode": { "type": "string" },
                "country": { "type": "string" }
            },
            "additionalProperties": false
        }
}

💠refs

The $ref keyword may be used to create recursive schemas that refer to themselves. For example, you might have a person schema that has an array of children, each of which are also person instances.

{
  ... // MORE CODE OMITTED FOR BREVITY
  "properties": {
    "name": { "type": "string" },
    "lastname": { "type": "string" },
    "children": {
      "type": "array",
      "items": { "$ref": "#" }
    }
  }
  ... // MORE CODE OMITTED FOR BREVITY
}

usage of recursive schema

{
  ... // MORE CODE OMITTED FOR BREVITY
  "name": "Elizabeth",
  "lastname": "Thomas",
  "children": [
    {
      "name": "Charles",
      "lastname": "Evans",
      "children": [
        {
          "name": "William",
          "lastname": "Davies",
          "children": [
            { 
                "name": "George",
                "lastname": "Taylor", 
            },
            { 
                "name": "Charlotte",
                "lastname": "Brown",
            }
          ]
        },
        {
          "name": "Harry",
          "lastname": "Smith",
        }
      ]
    }
  ]
  ... // MORE CODE OMITTED FOR BREVITY
}

💠External refs

{
  ... // MORE CODE OMITTED FOR BREVITY!!
  "properties": {
    "previousLocation": {
          "$ref": "https://smart-data-models.github.io/data-models/common-schema.json#/definitions/Location-Commons/properties/location"
        },
  }
  ... // MORE CODE OMITTED FOR BREVITY
}

external schema section

{
  ... // MORE CODE OMITTED FOR BREVITY
  "properties": {
    "location": {
          "oneOf": [
            {
              "title": "GeoJSON Point",
              "type": "object",
              "required": [
                "type",
                "coordinates"
              ],
              "description": "GeoProperty. Geojson reference to the item. Point"
              ...
  }
  ... // MORE CODE OMITTED FOR BREVITY
}

💠arrays and defs combinations

{
  ... // MORE CODE OMITTED FOR BREVITY
 "properties": {
        "addressHistory": {
            "type": "array",
            "items": { "$ref": "#/$defs/address" }
        }
    },
    "additionalProperties": false,
    "$defs": {
        "address": {
            "type": "object",
            "properties": {
                "line1": { "type": "string" },
                "line2": { "type": "string" },
                "townOrCity": { "type": "string" },
                "region": { "type": "string" },
                "postalCode": { "type": "string" },
            },
            "additionalProperties": false
        }
    }
  ... // MORE CODE OMITTED FOR BREVITY
}

💠defs with enums

{
  ... // MORE CODE OMITTED FOR BREVITY
 "properties": {
    "shipping_address": { "$ref": "/schemas/address" },
    "billing_address": { "$ref": "/schemas/address" }
     },
    "additionalProperties": false,
    "$defs": {
            "address": {
                "$id": "https://example.com/schemas/address",
                "$schema": "http://json-schema.org/draft-07/schema#",
                "type": "object",
                "properties": {
                    "street_address": { "type": "string" },
                    "city": { "type": "string" },
                    "state": { "$ref": "#/definitions/state" }
                },
                "required": ["street_address", "city", "state"],
                "definitions": {
                        "state": { "enum": ["CA", "NY", "... etc ..."] }
                }
            }
    }
  ... // MORE CODE OMITTED FOR BREVITY
}

💠strings with enums

{
  ... // MORE CODE OMITTED FOR BREVITY
 "properties": {
        "type": {
                "type": "string",
                "description": "Property. Indicates whether the vehicle is been used for special purposes, like commercial rental, driving school, or as a taxi. The legislation in many countries requires this information to be revealed when offering a car for sale. Model:'https://schema.org/vehicleSpecialUsage'. Enum:'ambulance, fireBrigade, military, police, schoolTransportation, taxi, trashManagement'",
                "enum": [
                    "Bus", "Car", "Caravan", "Dumper", "E-Bike", "E-Moped", "E-Scooter", "E-Motorcycle", "FireTender",
                ]
            },
  ... // MORE CODE OMITTED FOR BREVITY
}

Another example

{
  ... // MORE CODE OMITTED FOR BREVITY
 "properties": {
        "deviceBatteryStatus": {
          "type": "string",
          "enum": [
            "connected",
            "disconnected"
          ],
          "description": "Property. Model:'https://schema.org/Text'. Gives the Battery charging status of the reporting device. Enum:'connected, disconnected'"
        },
 },
  ... // MORE CODE OMITTED FOR BREVITY
}

💠array with enums

{
  ... // MORE CODE OMITTED FOR BREVITY
 "properties": {
        "category": {
            "type": "array",
            "description": "Property. Vehicle category(ies) from an external point of view. This is different than the vehicle type (car, lorry, etc.) represented by the `vehicleType` property. Model:'https://schema.org/Text'. Enum:'municipalServices, nonTracked, private, public, specialUsage, tracked'. Tracked vehicles are those vehicles which position is permanently tracked by a remote system. Or any other needed by an application They incorporate a GPS receiver together with a network connection to periodically update a reported position (location, speed, heading ...)",
            "items": {
                "type": "string",
                "enum": [
                "municipalServices",
                "nonTracked",
                "private",
                "public",
                "specialUsage",
                "tracked"
                ]
            }
        },
  ... // MORE CODE OMITTED FOR BREVITY
}

💠Reusing common types

In the next example, we constrained all of our types to a string of length 1-256.

{
  ... // MORE CODE OMITTED FOR BREVITY
 "properties": {
        "familyName": {
            "type": "string",
            "minLength": 1,
            "maxLength": 256
        },
        "givenName": {
            "type": "string",
            "minLength": 1,
            "maxLength": 256
        },
        "otherNames": {
            "type": "string",
            "minLength": 1,
            "maxLength": 256
        },
  ... // MORE CODE OMITTED FOR BREVITY
}

We can simplify this by re-using a reference to a common schema with the $ref keyword.

{
  ... // MORE CODE OMITTED FOR BREVITY
 "properties": {
        "properties": {
            "familyName": { "$ref": "#/$defs/constrainedString" },
            "givenName": { "$ref": "#/$defs/constrainedString" },
            "otherNames": { "$ref": "#/$defs/constrainedString" },
        },
 "$defs": {
    "constrainedString": {
      "type": "string",
      "minLength": 1,
      "maxLength": 256
    }
  }
  ... // MORE CODE OMITTED FOR BREVITY
}

💠object type

{
...// MORE CODE OMITTED FOR BREVITY
"properties": {
                "municipalityInfo": {
                "type": "object",
                "description": "Property. Model:'https://schema.org/Text. Municipality information corresponding to this observation",
                "properties": {
                    "district": {
                        "type": "string",
                        "description": "Property. Model:'https://schema.org/Text'. District name corresponding to this observation"
                        },
                    "ulbName": {
                        "type": "string",
                        "description": "Property. Model:'https://schema.org/Text'. Name of the Urban Local Body corresponding to this observation"
                        },
                    "cityId": {
                        "type": "string",
                        "description": "Property. Model:'https://schema.org/Text'. City ID corresponding to this observation"
                        },
                    "wardId": {
                        "type": "string",
                        "description": "Property. Model:'https://schema.org/Text'. Ward ID corresponding to this observation"
                        },
                    "stateName": {
                        "type": "string",
                        "description": "Property. Model:'https://schema.org/Text'. Name of the state corresponding to this observation"
                        },
                    "cityName": {
                        "type": "string",
                        "description": "Property. Model:'https://schema.org/Text'. City name corresponding to this observation"
                        },
                    "zoneName": {
                        "type": "string",
                        "description": "Property. Model:'https://schema.org/Text'. Zone name corresponding to this observation"
                        },
                    "zoneId": {
                        "type": "string",
                        "description": "Property. Model:'https://schema.org/Text'. Zone ID corresponding to this observation"
                        },
                    "wardName": {
                        "type": "string",
                        "description": "Property. Model:'https://schema.org/Text'. Ward name corresponding to this observation"
                        },
                    "wardNum": {
                        "type": "number",
                        "description": "Property. Model:'https://schema.org/Number'. Ward number corresponding to this observation"
                        }
                }
               }
},
...// MORE CODE OMITTED FOR BREVITY
}

💠allOf

To validate against allOf, the given data must be valid against all of the given subschemas. The allOf keyword is used to specify that a given instance must validate against all of the subschemas provided within an array. It’s essentially a logical "AND" operation where all conditions must be met for validation to pass.

{
...// MORE CODE OMITTED FOR BREVITY
"allOf": [
    { "type": "string" },
    { "maxLength": 5 }
  ]
...// MORE CODE OMITTED FOR BREVITY
}

💠oneOf

To validate against oneOf, the given data must be valid against exactly one of the given subschemas.

{
...// MORE CODE OMITTED FOR BREVITY
"properties": {
        "SINGLE_CHOICE": {
            "type": "string",
            "title": "Single choice",
            "description": "Some description",
            "oneOf": [
                    {
                    "const": "Yes",
                    "title": "Yes"
                    },
                    {
                    "const": "No",
                    "title": "No"
                    }
            ]
        },
},
...// MORE CODE OMITTED FOR BREVITY
}

Another example

{
...// MORE CODE OMITTED FOR BREVITY
"oneOf": [
    { "type": "number", "multipleOf": 5 },
    { "type": "number", "multipleOf": 3 }
  ]
...// MORE CODE OMITTED FOR BREVITY
}

Another example

{
...// MORE CODE OMITTED FOR BREVITY
"properties": {
        "speed": {
            "oneOf": [
                {
                "type": "number",
                "minimum": 0
                },
                {
                "type": "number",
                "minimum": 1,
                "maximum": 75
                }
            ],
            "description": "Property. Denotes the magnitude of the horizontal component of the vehicle's current velocity and is specified in Kilometers per Hour. If provided, the value of the speed attribute must be a non-negative real number. `-1` MAY be used if speed is transiently unknown for some reason. Model:'https://schema.org/Number'. Units:'Km/h'"
        },
},
...// MORE CODE OMITTED FOR BREVITY
}

💠anyOf

To validate against anyOf, the given data must be valid against any (one or more) of the given subschemas.

{
...// MORE CODE OMITTED FOR BREVITY
"anyOf": [
    { "type": "string", "maxLength": 5 },
    { "type": "number", "minimum": 0 }
  ]
...// MORE CODE OMITTED FOR BREVITY
}

Another example

{
...// MORE CODE OMITTED FOR BREVITY
"properties": {
        "refVehicleModel": {
            "anyOf": [
                {
                "type": "string",
                "minLength": 1,
                "maxLength": 256,
                "pattern": "^[\\w\\-\\.\\{\\}\\$\\+\\*\\[\\]`|~^@!,:\\\\]+$",
                "description": "Property. Identifier format of any NGSI entity"
                },
                {
                "type": "string",
                "format": "uri",
                "description": "Property. Identifier format of any NGSI entity"
                }
            ],
            "description": "Relationship. Model:'https://schema.org/URL'. Reference to a VehicleModel"
        },
},
...// MORE CODE OMITTED FOR BREVITY
}

💠Third-party solutions

📚Acknowledgments

To review

About

Repository for documenting the use of the JSON Schema tool.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published