[英]Json validation oneof validation
所以我有这个 json
{
"f1":"John",
"f2":"whatever",
"f3":"abc"
}
我想验证它,因为f1
, f2
, f3
应该只存在一个。 如果f1
、 f2
和f3
都不存在,那么它应该通过。
就像是,
{
"f1":"John",
}
经过
{
"f1":"John",
"f2":"whatever",
}
失败
{
"f1":"John",
"f2":"whatever",
"f3":"abc"
}
失败
{}
经过
这是我写的代码,但它失败了
{
"allOf": [
{
"if": {
"required": [
"f1"
]
},
"then": {
"not": {
"required": [
"f2", "f3"
]
}
}
},
{
"if": {
"required": [
"f3"
]
},
"then": {
"not": {
"required": [
"f2", "f1"
]
}
}
},
{
"if": {
"required": [
"f2"
]
},
"then": {
"not": {
"required": [
"f3", "f1"
]
}
}
}
]
}
编辑:架构https://jsonschema.dev/s/eN6Db的片段
根据您给定的要求,您无需检查定义的其他属性。 像这样的模式就足够了:
{
"type": "object",
"$schema": "http://json-schema.org/draft-07/schema#",
"description": "JSON schema generated with JSONBuddy https://www.json-buddy.com",
"properties": {
"f1": {
"type": "string"
},
"f2": {
"type": "string"
},
"f3": {
"type": "string"
}
},
"minProperties": 0,
"maxProperties": 1,
"additionalProperties": false
}
但是,如果您还需要此级别的其他属性,则此方法不起作用。
您在这里有两个选择。 您可以将else: false
添加到您的每个子模式( demo )或者,删除条件检查并使用oneOf
。 您还必须添加一个子模式以允许空对象。 第二种方法可能更可取。
这是架构和演示。
{
"oneOf": [
{
"additionalProperties": false
},
{
"required": [
"f1"
],
"not": {
"required": [
"f2",
"f3"
]
}
},
{
"required": [
"f3"
],
"not": {
"required": [
"f2",
"f1"
]
}
},
{
"required": [
"f2"
],
"not": {
"required": [
"f3",
"f1"
]
}
}
]
}
使用dependencies
( dependentSchemas
if >= 2019-09) 关键字来表达这种约束有一个简洁的小技巧。
{
"type": "object",
"properties": {
"f1": {},
"f2": {},
"f3": {}
},
"dependencies": {
"f1": { "not": { "required": ["f2"] } },
"f2": { "not": { "required": ["f3"] } },
"f3": { "not": { "required": ["f1"] } }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.