基于 属性 值的条件 Json 模式验证
Conditional Json Schema validation based on property value
我有如下输入 json,
{
"results": [
{
"name": "A",
"testA": "testAValue"
}
]
}
条件是,如果 'name' 的值为 'A',则 'testA' 应该是必填字段,如果 'name' 的值为 'B' , 那么 'testB' 应该是必填字段。
这是我试过的 Json 模式,但它没有按预期工作,
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"required": [
"results"
],
"properties": {
"results": {
"type": "array",
"oneOf": [
{
"$ref": "#/definitions/person"
},
{
"$ref": "#/definitions/company"
}
]
}
},
"definitions": {
"person": {
"type": "object",
"required": [
"name",
"testA"
],
"properties": {
"name": {
"type": "string",
"enum": [
"A"
]
},
"testA": {
"type": "string"
}
}
},
"company": {
"type": "object",
"required": [
"name",
"testB"
],
"properties": {
"name": {
"type": "string",
"enum": [
"B"
]
},
"testB": {
"type": "string"
}
}
}
}
}
也在 JSON 架构中尝试使用 "dependecies",但未能找到正确的解决方案。
对于实现上述用例的示例 JSON 模式的任何帮助/变通方法,我们将不胜感激。
你很接近。您的 oneOf
需要在 items
关键字中。
{
"type": "array",
"items": {
"oneOf": [
{ "$ref": "#/definitions/person" },
{ "$ref": "#/definitions/company" }
]
}
}
我有如下输入 json,
{
"results": [
{
"name": "A",
"testA": "testAValue"
}
]
}
条件是,如果 'name' 的值为 'A',则 'testA' 应该是必填字段,如果 'name' 的值为 'B' , 那么 'testB' 应该是必填字段。
这是我试过的 Json 模式,但它没有按预期工作,
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"required": [
"results"
],
"properties": {
"results": {
"type": "array",
"oneOf": [
{
"$ref": "#/definitions/person"
},
{
"$ref": "#/definitions/company"
}
]
}
},
"definitions": {
"person": {
"type": "object",
"required": [
"name",
"testA"
],
"properties": {
"name": {
"type": "string",
"enum": [
"A"
]
},
"testA": {
"type": "string"
}
}
},
"company": {
"type": "object",
"required": [
"name",
"testB"
],
"properties": {
"name": {
"type": "string",
"enum": [
"B"
]
},
"testB": {
"type": "string"
}
}
}
}
}
也在 JSON 架构中尝试使用 "dependecies",但未能找到正确的解决方案。
对于实现上述用例的示例 JSON 模式的任何帮助/变通方法,我们将不胜感激。
你很接近。您的 oneOf
需要在 items
关键字中。
{
"type": "array",
"items": {
"oneOf": [
{ "$ref": "#/definitions/person" },
{ "$ref": "#/definitions/company" }
]
}
}