Mutually exclusive property groups

时光毁灭记忆、已成空白 提交于 2019-12-01 05:57:50

You can phrase your constraints as:

  • either: both "a" and "b" are present, and "c" is not present
  • or: neither "a" nor "b" is present. ("c" may or may not be present)

Saying "neither" in the second point is a bit verbose. Here, we've expressed it using allOf/not. (Note: you can't factor them into a single required clause here, because you need a separate not for each one.)

{
    "oneOf": [
        {
            "required": ["a", "b"],
            "not": {"required": ["c"]}
        },
        {
            "allOf": [
                {
                    "not": {"required": ["a"]}
                },
                {
                    "not": {"required": ["b"]}
                }
            ]
        }
    ]
}

Alternative structure

There's also another way to say "neither", which is actually to use oneOf again. Since you must pass exactly one of a oneOf clause, if one of the entries is {} (passes everything), then all the other options are banned.

While it's slightly more concise, it's possibly slightly less intuitive to read:

{
    "oneOf": [
        {
            "required": ["a", "b"],
            "not": {"required": ["c"]}
        },
        {
            "oneOf": [
                {},
                {"required": ["a"]},
                {"required": ["b"]}
            ]
        }
    ]
}

Another alternative is to use the schema dependencies declaration:

   "dependencies": {
     "c": {
       "allOf": [
       { 
         "not": { "required": [ "a" ] }
       },
       { 
         "not": { "required": [ "b" ] }
       }
     ]
     }, 
     "a": {
       "allOf": [
       { 
         "not": { "required": [ "c" ] }
       },
       { 
         "required": [ "b" ]
       }
     ]
     },
     "b": {
       "allOf": [
       { 
         "not": { "required": [ "c" ] }
       },
       { 
         "required": [ "a" ]
       }
     ]
     }
   }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!