您的dependencies 应定义为对象{} 而不是数组[]。您只需要删除外部方括号:
"dependencies": {
"credit_card": ["billing_address"]
}
总的来说,这给出了以下架构:
{
"type": "object",
"properties": {
"name": {
"type": ["string", "null"]
},
"credit_card": {
"type": ["string", "null"]
},
"billing_address": {
"type": ["string", "null"]
}
},
"dependencies": {
"credit_card": ["billing_address"]
}
}
使用上述模式,以下 JSON 是有效的:
{
"name": "Abel",
"credit_card": "1234...",
"billing_address": "some address here..."
}
但是下面的 JSON 无效:
{
"name": "Abel",
"credit_card": "1234"
}
您可以使用在线验证器(例如 this one)来测试这些。
您可能还需要考虑删除您在架构中使用的null 值。例如,通过使用:
{
"type": "object",
"properties": {
"name": {
"type": "string",
},
"credit_card": {
"type": "string",
},
"billing_address": {
"type": "string",
}
},
"dependencies": {
"credit_card": ["billing_address"]
}
}
使用此修改后的架构,您现在还会收到 JSON 验证错误,如下所示:
{
"name": "Abel",
"credit_card": null,
"billing_address": "some address here..."
}
更新 - 两个字段都存在但为空:
如果credit_card 和billing_address 都为空,则可以使用条件验证(添加到下面架构的末尾)来处理这种情况:
{
"type": "object",
"properties": {
"name": {
"type": ["string", "null"]
},
"credit_card": {
"type": ["string", "null"]
},
"billing_address": {
"type": ["string", "null"]
}
},
"dependencies": {
"credit_card": ["billing_address"]
},
"if": {
"properties": { "credit_card": { "const": null } }
},
"then": {
"properties": { "billing_address": { "const": null } }
}
}
现在,以下内容也将有效:
{
"name": "Abel",
"credit_card": null,
"billing_address": null
}
一个警告说明:这使用了 JSON Schema 规范的一个相对较新的特性。我上面提到的在线验证器支持它 - 但我不知道你可能使用的任何验证器是否支持它。