my goal is to create a schema containing any number array of items where each individual item has "key" string property based on which the "data" property schema changes.
Below is the schema I use to validate and the JSON I expect the validation to fail. As you can see the given example contains properties reserved for different condition, so I expected it to fail.
Any ideas how can I improve the schema so it validates properly?
{
"$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'
}
}
]
}
This might help: