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"
                  }
               }
             }
            }
          }
1
  • 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 Commented Nov 26, 2019 at 7:10

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.