【问题标题】:json schema with one mandatory property and at least one another not typed checked具有一个强制属性且至少另一个未键入的 json 模式
【发布时间】:2016-08-20 07:34:23
【问题描述】:

我在 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 属性

标签: json schema jsonschema


【解决方案1】:

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"] }
    ]
  }
}

【讨论】:

    猜你喜欢
    • 2018-01-02
    • 2021-02-18
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 2022-01-13
    相关资源
    最近更新 更多