Json Schema Examples
Last updated:WIP Alert This is a work in progress. Current information is correct but more content will probably be added in the future.
Unless otherwise noted, examples are written against json-schema v4
Simplest possible schema
A person object having "name" and "age" attributes, both required.
{
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "Person object",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "number"
}
},
"required":["name","age"]
}
Matching documents:
{
"name":"john smith",
"age": 72
}
"anyOf", "allOf" and "oneOf" keywords
"oneOf"
can be used to provide an array of criteria where, if exactly one of them is valid, the whole block is valid.
For example, if you need multiple required rules, you could do this:
Note that every entry in the array must be a valid schema attribute and, therefore, a json object. So the
"required"
attribute is nested in"oneOf"
and not the other way around.
{
"$schema": "http://json-schema.org/schema#",
"title": "example schema",
"type": "object",
"properties": {
// define properties here
},
"oneOf":[
{
"required": [
"name",
"dateOfBirth"
]
},
{
"required": [
"name",
"age"
]
}
]
}
As per the exampe above, objects having ("name"
AND "age"
) OR ("name"
AND "dateOfBirth"
) attributes are considered valid.
However, an object having "name"
, "age"
and "dateOfBirth"
attributes would fail.
Similarly to "oneOf"
, using "anyOf"
and "allOf"
would consider objects valid when they match one or more or all of the specified required attributes, respectively.
"$ref" and "definitions"
Your root object may have a "definitions"
attribute containing stuff you want to share across different parameters.
For example, you have several attributes in your object, which you want to be valid dates, as defined by one of these patterns:
"^now([+-][0-9]+[smhdMy])?$"
(matches dynamic dates like "now", "now-1m", "now+1h" and so on)"^[12][0-9]{3}-[01][0-9]-[01][0-9]$"
(matches full dates like "2016-08-17", "1999-01-25" and so on)
You probably know that you can specify a "pattern"
you want attributes to match against, but it would be annoying (and error-prone) to have to define it for every attribute you have.
**You can use
"definitions"
to define common attributes and validation rules and then reference them using"$ref"
Example: define date patterns once and reference them using "$ref"
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Example using definitions and references",
"type": "object",
"properties": {
"from": {
"$ref": "#/definitions/timestampDef"
},
"to":{
"$ref": "#/definitions/timestampDef"
}
},
"definitions":{
"timestampDef":{
"type": "string",
"oneOf":[
{
"pattern": "^now([+-][0-9]+[smhdMy])?$"
},
{
"pattern": "^[0-9]{12,14}$"
}
]
}
}
}
See also
Json Schema Lint - Online tool to validate Json Schemas