我想要创建一个模式,其中我将在"oneOf“中有多个对象,其中有许多anyOf格式的对象,其中一些键可以是必需的类型(这个部分可以工作)我的模式:-
{
"description": "schema v6",
"type": "object",
"oneOf": [
{
"properties": {
"Speed": {
"items": {
"anyOf": [
{
"$ref": "#/definitions/speed"
},
{
"$ref": "#/definitions/SituationType"
}
]
},
"required": [
"speed"
]
}
},
"additionalProperties": false
}
],
"definitions": {
"speed": {
"description": "Speed",
"type": "integer"
},
"SituationType": {
"type": "string",
"description": "Situation Type",
"enum": [
"Advice",
"Depend"
]
}
}
}但是,当我试图验证这个模式时,我可以验证一些不正确的值,比如
{
"Speed": {
"speed": "ABC",//required
"SituationType1": "Advisory1" //optional but key needs to be correct
}
}我所期待的正确反应是
{
"Speed": {
"speed": "1",
"SituationType": "Advise"
}
}发布于 2018-10-18 13:31:39
首先,您需要正确地设置模式类型,否则植入可能假设您使用的是最新的JSON版本(当前是草案-7)。
因此,在模式根中,您需要以下内容:
"$schema": "http://json-schema.org/draft-06/schema#",第二,只有当目标是数组时,items才适用。目前,您的架构只检查以下内容:
如果根对象具有“速度”属性,则必须有“速度”键。根对象不得具有任何其他属性。
没别的事了。
您对definitions的使用以及如何引用它们可能不是您想要的。
看起来,您希望Speed包含必须是整数的speed,以及选项式SituationType,它必须是字符串,受枚举限制,没有其他限制。
下面是基于此的模式,它根据给定的示例数据正确传递和失败:
{
"$schema": "http://json-schema.org/draft-06/schema#",
"type": "object",
"oneOf": [
{
"properties": {
"Speed": {
"properties":{
"speed": {
"$ref": "#/definitions/speed"
},
"SituationType": {
"$ref": "#/definitions/SituationType"
}
},
"required": [
"speed"
],
"additionalProperties": false
}
},
"additionalProperties": false
}
],
"definitions": {
"speed": {
"description": "Speed",
"type": "integer"
},
"SituationType": {
"type": "string",
"description": "Situation Type",
"enum": [
"Advice",
"Depend"
]
}
}
}您需要为Speed定义属性,因为否则无法阻止附加属性,因为additionalProperties只受相邻的properties键的影响。我们希望在草案-8中创建一个新关键字来支持这种行为,但是在您的示例(重大的吉突问题)中似乎不需要它。
现在,将additionalProperties false添加到Speed架构可以防止该对象中的其他键。
我怀疑,考虑到您的问题标题,这里可能会有更多的模式,您已经为这个问题简化了它。如果您有一个包含更复杂问题的更详细的模式,我也很乐意提供帮助。
https://stackoverflow.com/questions/52873080
复制相似问题