json 具有一项强制性 属性 和至少另一项未键入检查的架构

json schema with one mandatory property and at least one another not typed checked

我在 json 中有这个对象,我想用 json 模式验证它

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

lookup 属性 是强制性的,然后我至少需要 shortreferenceguid 或两者兼而有之。

{
    "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

anyOf 将在找到一个匹配的架构后立即停止验证。如果您将所有 属性 声明拉入架构的根目录并且在 anyOf 架构中只有 required,它应该会按预期工作。这样,所有属性都将进行类型检查,并且 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"] }
    ]
  }
}