JSON Schema:必填字段的XOR

时间:2016-07-06 10:16:43

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

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

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

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

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

2 个答案:

答案 0 :(得分:2)

根本不优雅,但我认为你可以从allOfoneOf破解它。类似的东西:

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

答案 1 :(得分:0)

您现在可能已经对此进行了排序,但这可以使用该字段的oneOf上的type进行操作。

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