【问题标题】:JSON Schema: XOR on required fieldsJSON Schema:对必填字段进行异或
【发布时间】:2016-07-06 10:16:42
【问题描述】:

JSON 模式有a required property,它列出了 JSON 对象中的必填字段。例如,以下(简化的)模式验证向用户发送文本消息的调用:

{
  "type": "object",
  "properties": {
    "userId":    { "type": "string" },
    "text":      { "type": "string" },
  },
  "required": ["userId", "text"]
}

假设我想启用将消息发送给多个用户,即有一个 userId 字段或一个 userIds 数组(但不是两者都有或两者都没有)。有没有办法在 JSON Schema 中表达这样的条件?

当然,在这种情况下,有一些方法可以解决这个问题 - 例如,具有单个元素的 userId 数组 - 但一般情况是有趣且有用的。

【问题讨论】:

    标签: json jsonschema json-schema-validator required-field


    【解决方案1】:

    一点也不优雅,但我认为你可以从allOfoneOf 中破解它。比如:

     {
       "allOf" : [
          {
            "type" : "object",
            "properties" : {
              // base properties come here
            }
          },
          "oneOf" : [
            {
            "properties" : {
                 "userIds" : {"type" : "array"}
              },
              "required" : ["userIds"]
            },
            {
              "properties" : {
                 "userId" : {"type" : "number"}
              },
              "required" : ["userId"]
            }
          ]
       ]
    }
    

    【讨论】:

      【解决方案2】:

      您现在可能已经解决了这个问题,但这将在字段的type 上使用oneOf 来解决问题。

      {
        "type": "object",
        "properties": {
          "userId": {
            "oneOf": [
              {
                "type": "string"
              },
              {
                "type": "array",
                "items": {
                  "type": "string"
                }
              }
            ]
          },
          "text": {
            "type": "string"
          }
        },
        "required": ["userId", "text"]
      }
      

      【讨论】:

        猜你喜欢
        • 2018-06-12
        • 1970-01-01
        • 2020-01-13
        • 1970-01-01
        • 2021-06-22
        • 1970-01-01
        • 2018-12-11
        • 1970-01-01
        • 2014-08-02
        相关资源
        最近更新 更多