What is the difference between "required" vs "optional" in JSON Schema
Sometimes, I noticed the following JSON Schemas:
{
"type": "object",
"properties": {
"address": {
"type": "string",
"required": true
}
}
}
vs
{
"type": "object",
"properties": {
"address": {
"type": "string",
"optional": false
}
}
}
So what is the difference between required
vs optional
in the above example?
The IETF draft v4 of the JSON schema
only defines required
and does not include optional
.
To quote the section on required
from draft v4:
Valid values: The value of this keyword MUST be an array. This array MUST have at least one element. Elements of this array MUST be strings, and MUST be unique.
Conditions for successful validation: An object instance is valid against this keyword if its property set contains all elements in this keyword's array value.
In effect, using required
makes optional all properties for which
the name is not included in the given array of strings.
Actually, they are equivalent expressions, but using different versions of the standard.
optional
is from v2, required
is from v3. You should make sure you are using the correct one for your tool (although ideally you should move to v4 if you can).
This means that the object must have a non-undefined
value for the address
property (if required
).