我的目标是创建一个包含任意数量的项目数组的模式,其中每个单独的项目都有“key”字符串属性,“data”属性模式将根据该属性进行更改。
下面是我用来验证的架构以及我预计验证失败的 JSON。正如您所看到的,给定的示例包含为不同条件保留的属性,所以我预计它会失败。
有什么想法可以改进模式以使其正确验证吗?
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"components": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"anyOf": [
{
"if": {
required: ["key"],
"properties": {
"key": { "const": "x" }
}
},
"then": {
"required": ["prop1"],
"properties": {
"prop1": {
"type": "string"
}
}
}
},
{
"if": {
required: ["key"],
"properties": {
"key": { "const": "y" }
}
},
"then": {
"required": ["prop2"],
"properties": {
"prop2": {
"type": "string"
}
}
}
}
]
}
}
},
"required": [
"components"
],
}
{ components: [
{
key: "x",
data: {
prop2: 'prop'
}
},
{
key: "y",
data: {
prop1: 'prop'
}
}
]
}
这可能有帮助:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"components": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"properties": {
"key": {
"type": "string"
},
"data": {
"type": "object",
"oneOf": [
{
"if": {
"properties": {
"key": {
"const": "x"
}
},
"required": ["key"]
},
"then": {
"properties": {
"data": {
"required": ["prop1"],
"properties": {
"prop1": {
"type": "string"
}
}
}
}
}
},
{
"if": {
"properties": {
"key": {
"const": "y"
}
},
"required": ["key"]
},
"then": {
"properties": {
"data": {
"required": ["prop2"],
"properties": {
"prop2": {
"type": "string"
}
}
}
}
}
}
]
}
},
"required": ["key", "data"]
}
}
},
"required": [
"components"
]
}