Only allow properties that are declared in JSON schema

28,293

Solution 1

I believe what you need to do to achieve this is set additionalProperties to false. See the specification here

Solution 2

Inside your definition provide:

  • all required fields inside "required": []
  • and set "additionalProperties": false

DEMO:

without "additionalProperties": false: enter image description here

with "additionalProperties": false: enter image description here

Solution 3

FYI - it looks like v5 of the standard will describe a "ban unknown properties" validation mode.

So instead of making this requirement part of the format (which as Chris Pitman says in the comments, damages future extensibility), you can simply instruct your validator to flag unknown properties as errors. So, it's like a super-strict validation mode which is useful for dev.

Some validators already support this (e.g. tv4):

var result = tv4.validateMultiple(data, schema, checkRecursive, banUnknownProperties);

With this tool, checkRecursive should be used if your data might have circular references, and banUnknownProperties will do exactly what you want, without having to use "additionalProperties":false.

Share:
28,293
ipengineer
Author by

ipengineer

Updated on May 30, 2020

Comments

  • ipengineer
    ipengineer almost 4 years

    I am using json-schema and wanting to only allow properties that are declared in this file to pass validation. For instance if a user passes a "name" property in their json object it will fail this schema because "name" is not listed here as a property.

    Is there some function similar to "required" that will only allow the listed properties to pass?

    {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "Accounting Resource - Add Item",
    "type": "object",
    "properties": {
        "itemNumber": {
            "type":"string",
            "minimum": 3
        },
        "title": {
            "type":"string",
            "minimum": 5
        },
        "description": {
            "type":"string",
            "minimum": 5
        }
    },
    "required": [
        "itemNumber",
        "title",
        "description"
    ]
    }
    
  • OneHoopyFrood
    OneHoopyFrood over 4 years
    In the latest draft: json-schema.org/latest/…
  • eNca
    eNca over 2 years
    In the specification there is stated that The value of "additionalProperties" MUST be a valid JSON Schema. Can you specify, where it is stated that the value can be a boolean?
  • ponomy
    ponomy almost 2 years
    2 of the 3 schema validators I tried said 'true' is a valid JSON schema. ::shrug Also the doc you reference uses booleans for additionalProperties: json-schema.org/draft/2020-12/…