Json 如果另一个键等于某个值,则模式检查键是否存在(草稿 4)
Json schema check keys presence if another key equals some value (draft 4)
我想验证一个 json 键的存在,前提是另一个键存在并且等于某个值。
例如,在下面的 json 中,仅当 "key" 等于 "foo" 时,我才希望出现 "baz":
{
"id":"myid",
"key":"foo",
"baz":"baz!"
}
我可以简单地使用以下 json 模式(草稿 4)来验证它:
{
"properties":
{
"key":{
"type": "string",
"enum": ["foo", "bar"]
},
"baz":{
"type": "string"
},
"quuz":{
"type": "string"
}
},
"anyOf":
[
{
"properties":{
"key":{ "enum": ["foo"] }
},
"required": ["baz"]
},
{
"properties":{
"key":{ "enum": ["bar"] }
},
"required": ["quuz"]
}
]
}
下面的json也是有效的:
{
"id":"myid",
"key":"bar",
"quuz":"quuz!"
}
这是无效的("key" = "bar" 需要 "quuz"):
{
"id":"myid",
"key":"bar",
"baz":"baz!"
}
到目前为止,还不错。现在:如果缺少 "key" 键,我也需要 json 有效:
{
"id":"myid"
}
这不适用于上述架构,因为 "anyOf" 关键字设置 "required" 字段。
是否有可能获得 "anyOf or missing key" 行为?。草稿
有什么帮助吗?
您可以通过描述两个独占子模式来实现该逻辑,有和没有 key
:
{
"properties":
{
"key":{
"type": "string",
"enum": ["foo", "bar"]
},
"baz":{
"type": "string"
},
"quuz":{
"type": "string"
}
},
"oneOf":
[
{
"not": {"required": ["key"]}
},
{
"required": ["key"],
"anyOf": [
{
"properties":{
"key":{ "enum": ["foo"] }
},
"required": ["baz"]
},
{
"properties":{
"key":{ "enum": ["bar"] }
},
"required": ["quuz"]
}
]}
]
}
我想验证一个 json 键的存在,前提是另一个键存在并且等于某个值。
例如,在下面的 json 中,仅当 "key" 等于 "foo" 时,我才希望出现 "baz":
{
"id":"myid",
"key":"foo",
"baz":"baz!"
}
我可以简单地使用以下 json 模式(草稿 4)来验证它:
{
"properties":
{
"key":{
"type": "string",
"enum": ["foo", "bar"]
},
"baz":{
"type": "string"
},
"quuz":{
"type": "string"
}
},
"anyOf":
[
{
"properties":{
"key":{ "enum": ["foo"] }
},
"required": ["baz"]
},
{
"properties":{
"key":{ "enum": ["bar"] }
},
"required": ["quuz"]
}
]
}
下面的json也是有效的:
{
"id":"myid",
"key":"bar",
"quuz":"quuz!"
}
这是无效的("key" = "bar" 需要 "quuz"):
{
"id":"myid",
"key":"bar",
"baz":"baz!"
}
到目前为止,还不错。现在:如果缺少 "key" 键,我也需要 json 有效:
{
"id":"myid"
}
这不适用于上述架构,因为 "anyOf" 关键字设置 "required" 字段。
是否有可能获得 "anyOf or missing key" 行为?。草稿
有什么帮助吗?
您可以通过描述两个独占子模式来实现该逻辑,有和没有 key
:
{
"properties":
{
"key":{
"type": "string",
"enum": ["foo", "bar"]
},
"baz":{
"type": "string"
},
"quuz":{
"type": "string"
}
},
"oneOf":
[
{
"not": {"required": ["key"]}
},
{
"required": ["key"],
"anyOf": [
{
"properties":{
"key":{ "enum": ["foo"] }
},
"required": ["baz"]
},
{
"properties":{
"key":{ "enum": ["bar"] }
},
"required": ["quuz"]
}
]}
]
}