只允许在 JSON 模式中声明的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17530762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Only allow properties that are declared in JSON schema
提问by ipengineer
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.
我正在使用 json-schema 并且只想允许在此文件中声明的属性通过验证。例如,如果用户在其 json 对象中传递“name”属性,则此架构将失败,因为此处未将“name”列为属性。
Is there some function similar to "required" that will only allow the listed properties to pass?
是否有一些类似于“required”的函数只允许列出的属性通过?
{
"$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"
]
}
回答by Jules
回答by cloudfeet
FYI - it looks like v5 of the standard will describe a "ban unknown properties"validation mode.
仅供参考 - 看起来标准的 v5 将描述“禁止未知属性”验证模式。
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 validatorto flag unknown properties as errors. So, it's like a super-strict validation mode which is useful for dev.
因此,与其将此要求作为格式的一部分(正如 Chris Pitman 在评论中所说,这会损害未来的可扩展性),您可以简单地指示您的验证器将未知属性标记为错误。因此,它就像一种对开发人员有用的超严格验证模式。
Some validators already support this (e.g. tv4):
一些验证器已经支持这个(例如tv4):
var result = tv4.validateMultiple(data, schema, checkRecursive, banUnknownProperties);
With this tool, checkRecursiveshould be used if your data might have circular references, and banUnknownPropertieswill do exactlywhat you want, without having to use "additionalProperties":false.
使用此工具,checkRecursive如果您的数据可能具有循环引用,则应使用此工具,并且banUnknownProperties将完全按照您的意愿执行操作,而无需使用"additionalProperties":false.


