Adilmo
Adilmo

Reputation: 117

Issue with json schema oneOf validation ... Not able to get the right validation

I need help in validating json object with following constraint.

My object has four sub objects.

Valid Objects

Invalid objects

Only one out of obj2, obj3, obj4 can be present or none should be present.

Upvotes: 1

Views: 464

Answers (1)

Jason Desrosiers
Jason Desrosiers

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

Related Questions