Search code examples
pythonjsonvalidationjsonschemapython-jsonschema

JSON Schema throw validation error if invalid optional attribute


I have a json schema as shown below which has three properties height,weight and volume which are optional. But I want to do following additional check here:

  1. If any other attributes apart from height,weight and volume is passed then it should throw an error

Not sure how to achieve this since these are optional attributes.

  {
            "$schema": "http://json-schema.org/draft-04/schema#",
            "type": "object",
            "properties": {
              "options": {
                "type": "object",
                "properties": {
                  "height": {
                    "type": "number"
                  },
                  "weight": {
                    "type": "number"
                  },
                  "volume": {
                    "type": "number"
                  }
               }
             }
            }
          }

Solution

  • What you're looking for is the additionalProperties key. From JsonSchema docs

    The additionalProperties keyword is used to control the handling of extra stuff, that is, properties whose names are not listed in the properties keyword. By default any additional properties are allowed.

    So, this yould become:

     {
                "$schema": "http://json-schema.org/draft-04/schema#",
                "type": "object",
                "properties": {
                  "options": {
                    "type": "object",
                    "properties": {
                      "height": {
                        "type": "number"
                      },
                      "weight": {
                        "type": "number"
                      },
                      "volume": {
                        "type": "number"
                      }
                   },
                   "additionalProperties": false
                 }
                }
              }
    

    From my understanding, this is supported since draft 00, so it should be ok with draft 4, but just for you to know, the 8th version is here.