json模式有一个强制属性,至少另一个没有键入已检查

时间:2016-04-26 12:50:27

标签: json schema jsonschema

我在json中有这个对象,我想用json架构验证

"reference": {
    "lookup" : "opportunity",
    "shortreference": 93671,
    "guid": "4bb30c46-20ec-e511-9408-005056862bfb"
}

查找属性是必需的,然后我至少需要短引用 guid 或两者兼而有之。

{
    "reference": {
      "type": "object",
      "description": "opportunity reference",
      "properties": {
        "lookup": {
          "enum": [
            "employee",
            "opportunity",
            "serviceline",
            "account"
          ]
        }
      },
      "anyOf": [
        {
          "properties": {
            "shortreference": {
              "type": "integer"
            },
            "guid": {
              "type": "string"
            }
          }
        }
      ],
      "required": [
        "lookup"
      ]
    }
  }

修改 我使用以下架构修复了我的问题

{
    "reference": {
      "type": "object",
      "required": [
        "lookup"
      ],
      "properties": {
        "lookup": {
          "type": "string",
          "enum" : ["opportunity", "employee", "serviceline", "account"]
        }
      },
      "anyOf": [
        {
          "properties": {
            "shortreference": {
              "type": "integer"
            }
          },
          "required": [
            "shortreference"
          ]
        },
        {
          "properties": {
            "crmguid": {
              "type": "string"
            }
          },
          "required": [
            "crmguid"
          ]
        },
        {
          "properties": {
            "springim": {
              "type": "integer"
            }
          },
          "required": [
            "springim"
          ]
        }
      ]
    }

但是当我同时拥有这两个元素时,所有输入类型都没有输入: 如果“shortreference”:“12345”(字符串而不是整数),只要提供参数crmguid,就不会执行有关类型的检查。有没有办法强迫它。 (我正在使用AJV:https://github.com/epoberezkin/ajv

1 个答案:

答案 0 :(得分:4)

anyOf会在找到一个匹配的架构后立即停止验证。如果您将所有属性声明提取到模式的根目录并且required模式中只有anyOf,它应该按预期工作。这样,所有属性都将进行类型检查,anyOf将在找到至少一个必需属性时停止验证。

{
  "reference": {
    "type": "object",
    "required": ["lookup"],
    "properties": {
      "lookup": {
          "type": "string",
          "enum" : ["opportunity", "employee", "serviceline", "account"]
      },
      "shortreference": { "type": "integer" },
      "crmguid": { "type": "string" },
      "springim": { "type": "integer" }
    },
    "anyOf": [
      { "required": ["shortreference"] },
      { "required": ["crmguid"] },
      { "required": ["springim"] }
    ]
  }
}