In JSON schema, I want to add a validation that if the payload matches below
{
"key1": "value1",
"key1": "value2"
}
Then expect a third key "key3" with any value.
But if the value of key1 and key2 doesn't match value1, value2 respectively then key3 should not be present.
JSON schema looks like this
{
"$async": true,
"additionalProperties": false,
"properties": {
"key1": {
"type": "string"
},
"key2": {
"type": "string"
}
},
"required": ["key1"],
"allOf": [
{
"if": {
"properties": {
"key1": {
"const": "value1"
},
"key2": {
"const": "value2"
}
}
},
"then": {
"properties": {
"key3": {
"type": "string"
}
},
"required": ["key3"]
},
"else": {
}
}
]
}
Valid inputs are
{
"key1": "value1",
"key2": "value2",
"key3": "some-value"
}
--------
{
"key1": "value1",
"key2": "other-value"
}
---------
{
"key1": "value1"
}
---------
{
"key1": "other-value",
"key2": "value2"
}
---------
{
"key1": "other-value1",
"key2": "other-value2"
}
Invalid inputs are
{
"key1": "value1",
"key2": "value2". // key3 should be present
}
--------
{
"key1": "hello",
"key2": "world",
"unexpected-key": "value" // Any other key should not be allowed
}
--------
{
"key1": "value1",
"key2": "other-value",
"key3": "abc" // should not be present
}
---------
{
"key1": "other-value",
"key2": "value2",
"key3": "abc" // should not be present
}
---------
{
"key1": "other-value1",
"key2": "other-value2",
"key3": "abc" // should not be present
}
For below payload, JSON schema validator
{
"key1": "value1",
"key2": "value2",
"key3": "abc"
}
Throws below error
Property 'key3' has not been defined and the schema does not allow additional properties.
How do I achieve this conditional property?