我有以下 JSON 架构:
{
"type": "object",
"additionalProperties": false,
"properties": {
"abc": {
"type": "string"
},
"abc@mandatory": {
"type": "string"
},
"abc@optional": {
"type": "string"
},
"def": {
"type": "string"
},
"def@mandatory": {
"type": "string"
},
"def@optional": {
"type": "string"
}
},
"dependentSchemas": {
"abc": {
"required": [
"abc@mandatory"
]
},
"def": {
"required": [
"def@mandatory"
]
}
}
}
如果存在
abc@mandatory
,则强制属性 abc
存在。但我想要一条附加规则,规定如果 abc@mandatory
不存在,则
abc@optional
和 abc
都不能存在。我怎样才能实现这个目标?
我生成 JSON 模式,实际上有任意数量的此类组合,例如
def
和 def@...
。
背景:我想将我的数据转换成这个 XML 字符串:
<abc mandatory="foo" optional="bar">Some value</xyz>
包含
@
的属性将转换为 XML 属性。属性 mandatory
是 abc
的强制属性,属性 optional
是 abc
的可选属性。
但是,元素
abc
本身是可选的,如果它不存在,则属性 mandatory
和 optional
都没有意义。
我在 JSON Schema 中缺少两个功能:首先,我想为某个属性不存在的情况定义规则。其次,我想找到一种方法来禁止某些属性。 我可以通过指定永远不会评估为
true
的规则(例如 { "minLength": 1, "maxLength": 0 }
)来实现第二个功能,但这会导致令人困惑的错误消息。
allOf
关键字:
"allOf": [
{
"if": {
"required": ["xyz"]
},
"then": {
"required": ["xyz@mandatory"]
}
},
{
"if": {
"not": {
"required": ["xyz"]
}
},
"then": {
"not": {
"anyOf": [
{ "required": ["xyz@mandatory"] },
{ "required": ["xyz@optional"] }
]
}
}
}
]
xyz
不存在,但 xyz@mandatory
存在 ,并且 xyz
存在,但 xyz@mandatory
不存在 。两者都会导致验证错误。