数组的 Json 架构 if-then-else 验证

Json Schema if-then-else validation for array

提问人:wonuto 提问时间:7/2/2023 最后编辑:wonuto 更新时间:7/3/2023 访问量:57

问:

我有以下 Json 架构,其中用户类型可以是“employee”或“visitor”。如果 usertype 是 employee,我希望 batchId 是必需的,但我似乎根本无法做到这一点。任何帮助都是值得赞赏的。

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "title": "JSON Schema for role",
  "type": "object",
  "properties": {
    "usertype": {
      "type": "string",
      "enum": [
        "employee",
        "visitor"
      ]
    },
    "user": {
      "type": [
        "array"
      ],
      "items": {
        "type": "object",
        "properties": {
          "firstName": {
            "type": "string"
          },
          "lastName": {
            "type": "string"
          },
          "batchId": {
            "type": "string"
          }
        },
        "allOf": [
          {
            "if": {
              "properties": {
                "usertype": {
                  "enum": [
                    "employee"
                  ]
                }
              },
              "required": [
                "usertype"
              ]
            },
            "then": {
              "required": [
                "batchId"
              ]
            }
          }
        ],
        "required": [
          "firstName",
          "lastName"
        ]
      },
      "required": [
        "usertype",
        "user"
      ]
    }
  }
}

我有以下数据,我预计会失败,但它正在通过。

{
  "usertype": "employee",
  "user": [
    {
      "firstName": "John",
      "lastName": "Smith",
    },
    {
      "firstName": "Harry",
      "lastName": "Johnson",
      "batchId": "test"
    }
  ]
}

修改架构以在各个点具有 if then else。

json 验证 jsonschema json-schema-validator

评论


答:

0赞 Clemens 7/3/2023 #1

您必须将条件放在要检查的属性级别。无法在架构树中引用定义。

这将是一个可能的解决方案:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "description": "JSON schema generated with JSONBuddy https://www.json-buddy.com",
  "title": "JSON Schema for role",
  "type": "object",
  "properties": {
    "usertype": {
      "type": "string",
      "enum": [ "employee", "visitor" ]
    },
    "user": {
      "type": [ "array" ],
      "items": { "$ref": "#/definitions/userdef" }
    }
  },
  "required": [ "usertype", "user" ],
  "if": {
    "properties": {
      "usertype": { "enum": [ "employee" ] }
    }
  },
  "then": {
    "properties": {
      "user": {
        "type": [ "array" ],
        "items": {
          "allOf": [
            { "$ref": "#/definitions/userdef" },
            { "required": [ "batchId" ] }
          ]
        }
      }
    }
  },
  "definitions": {
    "userdef": {
      "type": "object",
      "properties": {
        "firstName": { "type": "string" },
        "lastName": { "type": "string" },
        "batchId": { "type": "string" }
      },
      "required": [ "firstName", "lastName" ]
    }
  }
}