1

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"
                  }
               }
             }
            }
          }
min2bro
  • 4,509
  • 5
  • 29
  • 55
  • Fetch the keys of the `properties` object, drop the valid ones (I'd use a set and set differences for that) and if there's anything left, throw the exception – Lukas Thaler Nov 26 '19 at 07:10

1 Answers1

2

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.

Er...
  • 526
  • 4
  • 10