我有一个情况,我正在有条件地验证所需的属性。
“不需要”未按预期工作。
如果“profile”为 profile1,则“rate”、“trick”和“tag”字段是必需的,并且“code”、“name”和“type”不应出现。
如果“profile”为 profile2,则需要“code”,不需要“rate”、“tag”和“trick”。
如果“profile”是 profile3,则不需要“rate”、“tag”、“trick”、“code”、“name”和“type”。
我正在使用架构草稿版本 4
架构
{
"type": "object",
"properties": {
"id": { "type": "integer" },
"url": { "type": "string" },
"profile": { "type": "string" },
"rate": { "type": "string" },
"trick": { "type": "boolean" },
"tag": { "type": "string" },
"type": { "type": "string" },
"name": { "type": "string" },
"code": { "type": "string" }
},
"additionalProperties": false,
"required": [ "url", "profile" ],
"oneOf": [
{
"properties": { "profile": { "enum": [ "profile1" ] } },
"not": { "required": ["type", "name", "code"] }
},
{
"properties": { "profile": { "enum": [ "profile2" ] } },
"allOf": [
{ "required": [ "code" ] },
{ "not": { "required": ["rate", "tag", "trick"] } }
]
},
{
"properties": { "profile": { "enum": ["profile3"] } },
"not": { "required": ["rate", "trick", "tag", "type", "name", "code"] }
}
]
}
有效输入
{
"id": 1,
"url": "url",
"profile": "profile2",
"type": "",
"name": "",
"code": ""
}
{
"id": 1,
"url": "url",
"profile": "profile3"
}
{
"id": 1,
"url": "url",
"profile": "profile1",
"rate": "",
"trick": false,
"tag": ""
}
无效输入
{
"url": "url",
"profile": "profile3",
"code": ""
}
最佳答案
我可以看到您是如何得出这种方法的,并且您可以使其发挥作用,但这不是最好的方法。
not
关键字反转值子模式的断言结果。
如果您采用 anyOf[2].not
架构...
{ "required": ["rate", "trick", "tag", "type", "name", "code"] }
这意味着,我相信您知道,所有这些属性都是必需的。
not
然后反转应用该子模式的结果。
因为在您希望验证失败的对象示例中,它只有该数组中的code
,因此它不满足required
约束。 p>
你可以让它 not > anyOf > [required > rates, required > trap...
等拥有许多子模式,但这会有点难看。
相反,您可以使用替代方法,并指定允许的内容...
您的 anyOf
将如下所示(演示: https://jsonschema.dev/s/zG9GF ):
"anyOf": [
false,
false,
{
"properties": {
"profile": {
"const": "profile3",
"id": true
}
},
"additionalProperties": false
}
]
您可能会发现使用 Draft-07 中的 if/then/else
关键字更为惯用,然后您可以使用 allOf
并设置 else<如果您不想为
profile
使用顶级枚举,请将/code> 值设置为 false
。
关于Json 架构 - 不需要则不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60450958/