JSON 架构 - 如果对象*不*包含特定的 属性,则有效
JSON schema - valid if object does *not* contain a particular property
是否可以设置一个 JSON 架构,它仍然允许 additionalProperties
但 不 匹配,如果一个非常特殊的 属性名称存在?换句话说,我需要知道是否有可能与 required
声明完全相反。
架构:
{
"type": "object",
"properties": {
"x": { "type": "integer" }
},
"required": [ "x" ],
"ban": [ "z" ] // possible?
}
匹配:
{ "x": 123 }
匹配:
{ "x": 123, "y": 456 }
不匹配:
{ "x": 123, "y": 456, "z": 789 }
我通过 "additionalProperties": false
禁止其他属性解决了这个问题,但使用 patternProperties
允许任何 属性 名字除了被禁止的名字。
{
"type": "object",
"properties": {
"x": { "type": "integer" }
},
"required": [ "x" ],
"patternProperties": {
"^(?!^z$).*": {}
},
"additionalProperties": false
}
你想做的可以使用not
关键字来实现。如果 not
模式验证,父模式将不会验证。
{
"type": "object",
"properties": {
"x": { "type": "integer" }
},
"required": [ "x" ],
"not": { "required": [ "z" ] }
}
有一个更简单的方法。定义如果 x 存在,则它不能满足任何模式。通过减少到荒谬 x 不能存在:
{
"properties" : {
"x" : {
"not" : {}
}
}
}
更新 2020/04/16:正如@Carsten 在评论中指出的那样,从草案版本 05 及更高版本开始,建议的架构可以简化如下:
{
"properties": {
"x": false
}
}
要指定缺少字段,您可以期望它的类型为 null
。
{
"type": "object",
"properties": {
"x": { "type": "integer" },
"z": { "type": "null" }
},
"required": [ "x" ]
}
您可以为该特定 属性 设置 null 类型:
z : {
"type": "null"
}
是否可以设置一个 JSON 架构,它仍然允许 additionalProperties
但 不 匹配,如果一个非常特殊的 属性名称存在?换句话说,我需要知道是否有可能与 required
声明完全相反。
架构:
{
"type": "object",
"properties": {
"x": { "type": "integer" }
},
"required": [ "x" ],
"ban": [ "z" ] // possible?
}
匹配:
{ "x": 123 }
匹配:
{ "x": 123, "y": 456 }
不匹配:
{ "x": 123, "y": 456, "z": 789 }
我通过 "additionalProperties": false
禁止其他属性解决了这个问题,但使用 patternProperties
允许任何 属性 名字除了被禁止的名字。
{
"type": "object",
"properties": {
"x": { "type": "integer" }
},
"required": [ "x" ],
"patternProperties": {
"^(?!^z$).*": {}
},
"additionalProperties": false
}
你想做的可以使用not
关键字来实现。如果 not
模式验证,父模式将不会验证。
{
"type": "object",
"properties": {
"x": { "type": "integer" }
},
"required": [ "x" ],
"not": { "required": [ "z" ] }
}
有一个更简单的方法。定义如果 x 存在,则它不能满足任何模式。通过减少到荒谬 x 不能存在:
{
"properties" : {
"x" : {
"not" : {}
}
}
}
更新 2020/04/16:正如@Carsten 在评论中指出的那样,从草案版本 05 及更高版本开始,建议的架构可以简化如下:
{
"properties": {
"x": false
}
}
要指定缺少字段,您可以期望它的类型为 null
。
{
"type": "object",
"properties": {
"x": { "type": "integer" },
"z": { "type": "null" }
},
"required": [ "x" ]
}
您可以为该特定 属性 设置 null 类型:
z : {
"type": "null"
}