Reputation: 117
I need help in validating json object with following constraint.
My object has four sub objects.
Valid Objects
{"obj" : { "obj1" : {}, "obj2" : {} } }
{"obj" : { "obj1" : {}, "obj3" : {} } }
{"obj" : { "obj1" : {}, "obj4" : {} } }
{"obj" : { "obj1" : {} } }
Invalid objects
{"obj" : { "obj1" : {}, "obj3" : {}, "obj4" : {} } }
{"obj" : { "obj1" : {}, "obj2" : {}, "obj4" : {} } }
{"obj" : { "obj1" : {}, "obj2" : {}, "obj3" : {} } }
{"obj" : { "obj1" : {}, "obj2" : {}, "obj3" : {}, "obj4" : {} } }
Only one out of obj2, obj3, obj4 can be present or none should be present.
Upvotes: 1
Views: 464
Reputation: 24489
Expressing mutually exclusive properties is pretty straightforward.
"oneOf": [
{ "required": ["obj2"] },
{ "required": ["obj3"] },
{ "required": ["obj4"] }
]
The tricky part is the "or none" constraint. You have to add a schema to the oneOf
that forbids all the properties. There are a couple ways to do this, but I think the following is the cleanest if not the most straightforward.
"oneOf": [
{
"properties": {
"obj2": false,
"obj3": false,
"obj4": false
}
},
{ "required": ["obj2"] },
{ "required": ["obj3"] },
{ "required": ["obj4"] }
]
An alternative is to use dependencies
instead of oneOf
.
"dependencies": {
"obj2": { "not": { "required": ["obj3"] } },
"obj3": { "not": { "required": ["obj4"] } },
"obj4": { "not": { "required": ["obj2"] } }
}
It's much less code and scales better, but it's not immediately clear what it's doing or how/why it works (it does work, I promise).
Upvotes: 2