json 架构,属性 存在与否的条件依赖
json schema, conditional dependency by property being present or not
我有这个架构要求,如果 A 和 B 不存在,C 必须存在,如果 C 存在,A 和 B 不应该存在。
例如:
{
"group1": {
"a": 10
},
"group2": {
"group3": {
"b": 30
}
},
"group4": {
"c": 20
}
}
如果 a
存在,b
和 c
不应出现在 json 中。
如果存在 b
和 c
,则 a
不应出现在 json.
中
我可以看到在 v6 json 架构规范中有一些关键字 switch
可以帮助满足此要求但无法使其工作。
在当前规范下是否可以进行此架构验证?
draft-06 是当前规范,但还没有条件。
draft-07 有 if/then/else,您可以使用它:
{
"if": {"required": ["a"]},
"then": {"not": {"$ref": "#/definitions/bc"}},
"else": {"$ref": "#/definitions/bc"},
"definitions": {
"bc": {
"anyOf": [
{"required": ["b"]},
{"required": ["c"]}
]
}
}
}
目前 if/then/else 在 Ajv 中支持 ajv-keywords。
任何条件都可以不用 if/then/else 使用关键字 anyOf、allOf 和 not 来表达:
{
"anyOf": [
{"allOf": [ifSchema, thenSchema]},
{"allOf": [{"not": ifSchema}, elseSchema]}
]
}
我有这个架构要求,如果 A 和 B 不存在,C 必须存在,如果 C 存在,A 和 B 不应该存在。
例如:
{
"group1": {
"a": 10
},
"group2": {
"group3": {
"b": 30
}
},
"group4": {
"c": 20
}
}
如果 a
存在,b
和 c
不应出现在 json 中。
如果存在 b
和 c
,则 a
不应出现在 json.
我可以看到在 v6 json 架构规范中有一些关键字 switch
可以帮助满足此要求但无法使其工作。
在当前规范下是否可以进行此架构验证?
draft-06 是当前规范,但还没有条件。 draft-07 有 if/then/else,您可以使用它:
{
"if": {"required": ["a"]},
"then": {"not": {"$ref": "#/definitions/bc"}},
"else": {"$ref": "#/definitions/bc"},
"definitions": {
"bc": {
"anyOf": [
{"required": ["b"]},
{"required": ["c"]}
]
}
}
}
目前 if/then/else 在 Ajv 中支持 ajv-keywords。
任何条件都可以不用 if/then/else 使用关键字 anyOf、allOf 和 not 来表达:
{
"anyOf": [
{"allOf": [ifSchema, thenSchema]},
{"allOf": [{"not": ifSchema}, elseSchema]}
]
}