Stealth Rabbi
Stealth Rabbi

Reputation: 10346

multiple conditionally required fields in json schema

I have a schema with a property that is required based if an enumeration matches some value. This works fine.

    "oneOf": [
      {
        "not" : {
          "properties": {
            "other-val": { "enum" : ["ABC"]}
          }
        }
      },
      { "required": ["ABC-detail"] } 
    ],

But, I'm trying to add a second field, DEF-detail, based on if the other-value enum is "DEF". I am not sure how to chain these dependencies up. I tried putting multiple oneOfs insde an allOf, but I can't add multiples of the same key to it.

Upvotes: 0

Views: 1184

Answers (2)

Jason Desrosiers
Jason Desrosiers

Reputation: 24409

That pattern is called "implication". You can easily declare more than one implication by combining them with allOf.

{
  "allOf": [
    {
      "anyOf": [
        {
          "not": {
            "properties": {
              "other-val": { "const": "ABC" },
            },
            "required": ["other-val"]
          }
        },
        { "required": ["ABC-detail"] }
      ]
    },
    ... another implication ...,
    ... another implication ...
  ]
}

If you are using draft-07 or later, you also have the if/then which is just a little syntactic sugar for implication.

{
  "if": {
    "properties": {
      "other-val": { "const": "ABC" }
    },
    "required": ["other-val"]
  },
  "then": { "required": ["ABC-detail"]
}

This pattern can be combined using allOf in the same way as implication.

Upvotes: 0

Stealth Rabbi
Stealth Rabbi

Reputation: 10346

A set of conditions in a oneOf works. But I don't think this excludes a DEF from having an abc-thing, for example, but this is OK in my case.

    "oneOf": [
      {
        "properties": {"other-val": {"enum": ["ABC"]}},
        "required": ["abc-thing"]
      },
      {
        "properties": {"other-val": {"enum": ["DEF"]}},
        "required": ["def-thing"]
      },  
      {
        "properties": {"other-val": {"enum": ["GHI"]}},
        "required": ["ghi-thing"]
      },            
      {
        "not": {"properties": {"other-val": {"enum": ["ABC", "DEF", "GHI"]}}}
      }
    ],

Upvotes: 0

Related Questions