如何使用
dependantRequired
绑定不同对象中的两个属性?
例如在以下架构中:
{
"$schema": "https://json-schema.org/draft/2019-09/schema",
"$id": "https://test.com/account",
"$vocabulary": {
"https://json-schema.org/draft/2019-09/vocab/core": true,
"https://json-schema.org/draft/2019-09/vocab/applicator": true,
"https://json-schema.org/draft/2019-09/vocab/validation": true,
"https://json-schema.org/draft/2019-09/vocab/meta-data": true,
"https://json-schema.org/draft/2019-09/vocab/format": false,
"https://json-schema.org/draft/2019-09/vocab/content": true
},
"$recursiveAnchor": true,
"title": "Core and Validation specifications meta-schema",
"properties": {
"bearer": {
"$anchor": "bearer_anchor",
"type": "string"
},
"profile": {
"type": "object",
"properties": {
"email": {
"type":"string"
},
"password": {
"type":"string"
},
"number": {
"type": "number"
},
"street_name": {
"type": "string"
},
"street_type": {
"enum": [
"Street",
"Avenue",
"Boulevard"
]
}
},
"dependentRequired": {
"email": [{"$ref": "https://test.com/account#bearer_anchor"}],
"password": [{"$ref": "https://test.com/account#bearer_anchor"}],
},
"additionalProperties": false
}
},
"additionalProperties": false
}
我试图定义
profile\email
和 profile\password
必须与属性 bearer
一起提供。
我确实尝试了很多方法来使用 $ref 作为绝对路径,如你所见。
您将无法使用
dependentRequired
来实现此目的,因为该关键字仅在同一架构中有效。但是,您可以使用 if
/then
。
这个,
"dependentRequired": {
"a": ["b"]
}
是模式的有效语法糖,
"if": { "required": ["a"] },
"then": { "required": ["b"] }
这比较冗长,但可以提供更多的表达能力。我们可以扩展它来检查
profile/email
属性。
"if": {
"properties": {
"profile": { "required": ["email"] }
}
"required": ["profile"]
},
"then": { "required": ["bearer"] }