如何在 JSON schema all 或 none 中表示多个可选属性?
How to express in JSON schema all or none for multiple optional properties?
我想表达所有或 none 可选属性都存在。例如
{
}
和
{
"a" : 1,
"b" : 2
}
应该都有效,但是
{
"a" : 1
}
和
{
"b" : 2
}
应该都是无效的。
这里是满足要求的架构:
{
"type": "object",
"properties": {
"a": {
"type": "integer"
},
"b": {
"type": "integer"
}
},
"oneOf": [{
"required": ["a", "b"]
}, {
"not": {
"anyOf": [{
"required": ["a"]
}, {
"required": ["b"]
}]
}
}],
"additionalProperties": false
}
另一种方法是在 JSON 中也表达属性属于一起,如
{
"parent": {
"a": 1,
"b": 2
}
}
其中 parent 存在或不存在,如果存在,则始终具有 a 和 b:
{
"type": "object",
"properties": {
"parent": {
"type": "object",
"properties": {
"a": {
"type": "integer"
},
"b": {
"type": "integer"
}
},
"required": ["a", "b"],
"additionalProperties": false
}
},
"additionalProperties": false
}
更简单的方法:
{
"properties:" {
"a" : {"type" : "integer"},
"b" : {"type" : "integer"}
},
"dependencies" : {
"a" : ["b"],
"b" : ["a"]
}
}
我想表达所有或 none 可选属性都存在。例如
{
}
和
{
"a" : 1,
"b" : 2
}
应该都有效,但是
{
"a" : 1
}
和
{
"b" : 2
}
应该都是无效的。
这里是满足要求的架构:
{
"type": "object",
"properties": {
"a": {
"type": "integer"
},
"b": {
"type": "integer"
}
},
"oneOf": [{
"required": ["a", "b"]
}, {
"not": {
"anyOf": [{
"required": ["a"]
}, {
"required": ["b"]
}]
}
}],
"additionalProperties": false
}
另一种方法是在 JSON 中也表达属性属于一起,如
{
"parent": {
"a": 1,
"b": 2
}
}
其中 parent 存在或不存在,如果存在,则始终具有 a 和 b:
{
"type": "object",
"properties": {
"parent": {
"type": "object",
"properties": {
"a": {
"type": "integer"
},
"b": {
"type": "integer"
}
},
"required": ["a", "b"],
"additionalProperties": false
}
},
"additionalProperties": false
}
更简单的方法:
{
"properties:" {
"a" : {"type" : "integer"},
"b" : {"type" : "integer"}
},
"dependencies" : {
"a" : ["b"],
"b" : ["a"]
}
}