只允许在 JSON 模式中声明的属性

我使用的是 json-schema,希望只允许在此文件中声明的属性通过验证。例如,如果用户在他们的 json 对象中传递一个“ name”属性,那么这个模式将会失败,因为这里没有将“ name”作为属性列出。

是否有类似于“必需”的函数只允许列出的属性传递?

{
"$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"
]
}
34286 次浏览

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

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.

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