56

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?

Cory
  • 14,865
  • 24
  • 57
  • 72
  • 8
    Note: this is a very old question, and `optional` no longer exists in the latest versions of JSON Schema. All properties are optional by default, and `required` is used to make them required. – Ether Sep 29 '21 at 16:33
  • Does this also mean that any key that has not been specified as allowed will be acceptable? How do you prohibit keys that have not been defined in the schema? – matanster Apr 28 '23 at 23:05

3 Answers3

43

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.

Peace Makes Plenty
  • 856
  • 10
  • 13
  • I can't say why but required seems to be empty in the link. The link is correct though – erikbstack Dec 04 '14 at 14:25
  • 2
    @erikb85 In the [link](http://json-schema.org/latest/json-schema-validation.html#anchor61), "5.4.3. required" is only an overall header; the two sub-sections underneath it detail the "required" keyword usage. – Peace Makes Plenty Dec 05 '14 at 17:14
  • Ah okay, that was really not clear just from looking at the doucment. Your formatting is way more clear in my eyes. – erikbstack Dec 08 '14 at 11:26
  • 2
    This link has an example and is a bit easier to follow: https://spacetelescope.github.io/understanding-json-schema/reference/object.html#required-properties – Collin Krawll Oct 20 '17 at 21:26
26

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).

cloudfeet
  • 12,156
  • 1
  • 56
  • 57
4

This means that the object must have a non-undefined value for the address property (if required).

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405