代码之家  ›  专栏  ›  技术社区  ›  shadowtalker

相互排斥的属性组合

  •  0
  • shadowtalker  · 技术社区  · 8 年前

    使用Jsonschema draft 6,我试图创建一个符合以下要求的模式:

    1. 属性A、B1、B2和B3是数字或数字 null
    2. 如果属性A存在且不为空,则属性B1、B2和B3必须不存在或为空
    3. 如果属性B1、B2和B3中的任何一个存在且不为空,则属性A必须为空或不存在。
    4. A、 B1、B2和B3可能都不存在

    合格文件的示例:

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

    不合格文件的示例:

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

    我看到了一些相关的问题,这些问题很有帮助,但并不能完全回答这个问题:

    以下是我当前的模式,它只强制约束#1和#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"}]
      }
    }
    

    正确的方法是什么?我是在要求一些不合理的东西吗?

    1 回复  |  直到 4 年前
        1
  •  2
  •   shadowtalker    4 年前
    {
      "$schema": "http://json-schema.org/draft-06/schema#",
      "oneOf": [
        {
          "properties": {
            "A": {"type": "number"},
            "B1": {"type": "null"},
            "B2": {"type": "null"},
            "B3": {"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"}
          }
        }
      ]
    }