dmi3y
dmi3y

Reputation: 3522

Json Schema, take into account unspecified properties

Is there is any ways to get heads ups about properties which are not described by schema into the standard. For example this schema:

{
   "description": "foo and bar", 
   "type": "object", 
    "properties": {
       "foo": {
        "type": "number"
       }, 
       "bar": {
        "type": "string", 
        "enum": [
            "a", 
            "b", 
            "c"
        ]
       }
   }
}

Will pass this JSON:

{
   "foo": 12345, 
   "bar": "a",
   "baz": 12312
}

Although it has baz property which is not the part of schema.

UPD: As of now I'm using tv4 library.

Upvotes: 1

Views: 753

Answers (1)

cloudfeet
cloudfeet

Reputation: 12863

Option 1: additionalProperties in the schema

If you want to explicitly constrained to the properties listed in a particular properties definition, then you can use additionalProperties: false. This will restrict data to only using properties defined in the nearby properties entry - in this case, "foo" and "bar".

However, use of additionalProperties impacts schema extension. If you (or someone else) extends this schema later (using allOf/$ref), then the data will still be subject to this schema - so will only be allowed to use "foo" and "bar", regardless of definitions elsewhere.

Option 2: banUnknownProperties flag in tv4

If the kind of complete lock-down is not desired, then you can use the banUnknownProperties flag in tv4 (docs). Basically, after validation, any properties that were not accounted-for by any schemas are raised as errors.

It was designed for cases when extra properties (including future variations/extensions) are theoretically allowed in the data format, but you want (for testing/warning purposes) to be alerted when extra properties show up where you're not expecting them.

Upvotes: 3

Related Questions