Mutually exclusive combinations of properties

三世轮回 提交于 2019-12-24 21:24:42

问题


Using Jsonschema draft 6, I'm trying to create a schema that conforms to the following:

  1. Properties A, B1, B2, and B3 are either numbers or null
  2. If property A is present and non-null, then properties B, C, and D must be either absent or null
  3. If any of properties B1, B2, and B3 are present and non-null, then property A must be null or absent.
  4. A, B1, B2, and B3 may all be absent

Examples of conforming documents:

{}

{"A": 1}

{"A": 1, "B2": null}

{"B1": 1}

{"B1": 1, "B2": 1, "B3": 1}

{"A": null, "B1": 1, "B2": 1, "B3": 1}

Examples of non-conforming documents:

{"A": 1, "B1": 2}

{"A": 1, "B1": null, "B2": 1}

I've seen some related questions that help but don't fully answer the question:

  • How to make anyOf a set of multually exclusive properties except one
  • Use json-schema to require or disallow properties based on another property value?
  • jsonSchema attribute conditionally required
  • How to define choice element in json schema when elements are optional?
  • How to define a JSON schema that requires at least one of many properties

Here is my current schema, which only enforces constraint #1 and #4:

{
  "$schema": "http://json-schema.org/draft-06/schema#",
  "properties": {
    "A": {"oneOf": [{"type": "null"}, {"type": "number"}],
    "B1": {"oneOf": [{"type": "null"}, {"type": "number"}],
    "B2": {"oneOf": [{"type": "null"}, {"type": "number"}],
    "B3": {"oneOf": [{"type": "null"}, {"type": "number"}]
  }
}

What is the right approach here? Am I asking for something unreasonable?


回答1:


{
  "$schema": "http://json-schema.org/draft-06/schema#",
  "oneOf": [
    {
      "properties": {
        "A": {"type": "number"},
        "B": {"type": "null"},
        "C": {"type": "null"},
        "D": {"type": "null"}
      },
      "required": ["A"]
    },
    {
      "properties": {
        "A": {"type": "null"},
        "B1": {"type": ["number","null"]},
        "B2": {"type": ["number","null"]},
        "B3": {"type": ["number","null"]}
      },
      "anyOf": [
        {"required": ["B1"]},
        {"required": ["B2"]},
        {"required": ["B3"]}
      ]
    },
    {
      "properties": {
        "A": {"type": "null"},
        "B1": {"type": "null"},
        "B2": {"type": "null"},
        "B3": {"type": "null"}
      }
    }
  ]
}


来源:https://stackoverflow.com/questions/50881764/mutually-exclusive-combinations-of-properties

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