I defined the following schema:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.com/schemas/test",
"type": "object",
"properties": {
"A": {
"type": "string"
}
},
"oneOf": [
{
"properties": {
"B": {
"type": "integer"
},
"C": {
"type": "boolean"
}
}
},
{
"properties": {
"D": {
"type": "string"
}
}
}
]
}
The idea is that the schema contains A, and either (B AND C) OR D. None of the elements are required (thus A is actually not part of the question/problem)
The following instance fails to validate:
{
"A": "Hello",
"D": "World"
}
It contains A (irrelevant, as not required anyway) and D, which should be covered by anyOf.
2
Answers
I believe you want
anyOf
instead ofoneOf
, becauseoneOf
checks for exactly one of the subschemas, but in your test instance you don’t have one of the subschemas. The docs are here: https://json-schema.org/understanding-json-schema/reference/combining#oneOf and you can test your schema here: https://json-schema.hyperjump.io/ which is where I findanyOf
works in your case.I suggest the following approach. Define all your properties together and then add a constraint to express your requirement.
Either "B" and "C" must be present or "D" must present, but not both. "A" may or may not be present with either option.