JSON 模式使 属性 有条件地需要
JSON Schema make property conditionally required
我当前的 JSON 架构定义是这样的
{
"properties": {
"account_type": {
"description": "account type",
"enum": [
"CURRENT",
"SAVINGS",
"DEMAT"
],
"type": "string"
},
"demat_account_number": {
"description": "demat_account_number",
"type": "string"
}
},
"required": [
"account_type"
],
"type": "object"
}
我的要求是如果 "account_type" = "DEMAT" 那么 "demat_account_number" 应该成为必需的属性。
我们有什么方法可以实现这个验证吗?
您可以使用 "oneOf"。这会强制符合规范的文档仅实现多种可能模式中的一种:
{
"oneOf":[
{
"properties":{
"account_type":{
"description":"account type",
"enum":[
"CURRENT",
"SAVINGS"
],
"type":"string"
}
},
"required":[
"account_type"
],
"type":"object"
},
{
"properties":{
"account_type":{
"description":"account type",
"enum":[
"DEMAT"
],
"type":"string"
},
"demat_account_number":{
"description":"demat_account_number",
"type":"string"
}
},
"required":[
"account_type",
"demat_account_number"
],
"type":"object"
}
]
}
一个不错的选择是使用 if
/then
。 if
块使用 const
断言来验证 account_type
具有 "DEMAT"
值。 then
块将 demat_account_number
添加到 required
属性。
{
"properties": {
"account_type": {
},
"demat_account_number": {
}
},
"required": [
"account_type"
],
"if": {
"properties": {
"account_type": {
"const": "DEMAT"
}
}
},
"then": {
"required": [
"demat_account_number"
]
}
}
我当前的 JSON 架构定义是这样的
{
"properties": {
"account_type": {
"description": "account type",
"enum": [
"CURRENT",
"SAVINGS",
"DEMAT"
],
"type": "string"
},
"demat_account_number": {
"description": "demat_account_number",
"type": "string"
}
},
"required": [
"account_type"
],
"type": "object"
}
我的要求是如果 "account_type" = "DEMAT" 那么 "demat_account_number" 应该成为必需的属性。
我们有什么方法可以实现这个验证吗?
您可以使用 "oneOf"。这会强制符合规范的文档仅实现多种可能模式中的一种:
{
"oneOf":[
{
"properties":{
"account_type":{
"description":"account type",
"enum":[
"CURRENT",
"SAVINGS"
],
"type":"string"
}
},
"required":[
"account_type"
],
"type":"object"
},
{
"properties":{
"account_type":{
"description":"account type",
"enum":[
"DEMAT"
],
"type":"string"
},
"demat_account_number":{
"description":"demat_account_number",
"type":"string"
}
},
"required":[
"account_type",
"demat_account_number"
],
"type":"object"
}
]
}
一个不错的选择是使用 if
/then
。 if
块使用 const
断言来验证 account_type
具有 "DEMAT"
值。 then
块将 demat_account_number
添加到 required
属性。
{
"properties": {
"account_type": {
},
"demat_account_number": {
}
},
"required": [
"account_type"
],
"if": {
"properties": {
"account_type": {
"const": "DEMAT"
}
}
},
"then": {
"required": [
"demat_account_number"
]
}
}