/
Validate - examples

Validate - examples

Cloud_Edition_button.webp

Below are three examples of JSON schema validation, demonstrating different use cases: required fields with basic string validation, pattern validation, and nested structures. For more details on using JSON schema, see https://json-schema.org/.

Example 1: Required fields and basic string validation

In this JSON schema, the following fields must be included in each record. A valid example is when the field "value" is of type string and is 2-3 characters long.

  • brand

  • model

  • color

  • date

{ "required": [ "brand", "color", "model", "date" ], "properties": { "value": { "type": "string", "minLength": 2, "maxLength": 3 } } }

This record matches all of the criteria:

{ "brand": "brand1", "model": "modelA", "color": "red", "date": "20 March 2019", "value": "cat" }

This record is discarded because hamster has more than 3 characters:

{ "brand": "brand1", "model": "modelA", "color": "red", "date": "20 March 2019", "value": "hamster" }

Example 2: Pattern validation

Pattern validation is done by specifying expressions that correlate with the desired functionality. In this example, the code checks for the presence of 6 digits and 3 uppercase characters: 

{ "type":"string", "pattern":"\\d{6}[A-Z]{3}" }

Another pattern validation example checks for the presence of a specific email address format: 

{ "type":"string", "pattern":".+@.+\\..+" }

Example 3: Nested structures

You need to use a different JSON schema structure for more complex use cases with nested structures like a nested array or object. To validate the following…

{ "brand": { "logoType": true, "name": "brandA" }, "model": { "year": "2004", "name": "modelA" }, "arrayWithString": ["a", "b", "c"] }

…use a JSON schema like:

{ "properties": { "brand": { "properties": { "logoType": { "type":"boolean" }, "name": { "type": "string" } } }, "model": { "properties": { "year": { "pattern": "^\\d{4}$" }, "name": { "type": "string" } } }, "arrayWithString": { "type": "array", "items": { "type": "string" } } } }