首页 > 解决方案 > 如何使用 Json Schema Validator 在特定条件下执行长度检查验证?

问题描述

我有如下所示的 json 模式结构。

{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "description": "My sample Json",
  "type": "object",
  "properties": {
    "eventId": {
      "description": "The event Indetifier",
      "type": [ "number", "string" ]
    },
    "serviceType": {
      "description": "The service type. It can be either ABC or EFG",
      "enum": [ "ABC", "EFG" ]
    },
    "parameters": { "$ref": "/schemas/parameters" }
  },
  "required": [ "eventId", "serviceType" ],
  "$defs": {
    "parameters": {
      "$id": "/schemas/parameters",
      "$schema": "http://json-schema.org/draft-07/schema#",
      "description": "Other Parameters",
      "type": "object",
      "properties": {
        "activityType": {
          "description": "The activity type",
          "type": [ "null", "string" ]
        },
        "activitySubType": {
          "description": "The activity sub type",
          "type": [ "null", "string" ]
        }
      }
    }
  }
}

现在我需要执行一些验证逻辑。

  1. 如果 eventId == "100" 和 serviceType == "ABC" 则 parameters.activityType 不应为 null,并且必须具有最小长度 10。
  2. 如果 eventId == "200" 和 serviceType == "EFG" 则 parameters.activitySubType 不应为空,并且必须具有最小长度 20。

我正在尝试使用“if then else”条件执行验证。我不确定如何在 Json Schema 验证器中添加它。

谁能帮我语法?有可能这样做吗?

标签: jsonjsonschema

解决方案


这绝对是可能的。对于第一个要求:

{
  ...
  "if": {
    "required": [ "eventId", "serviceType" ],
    "properties": {
      "eventId": {
        "const": "100"
      },
      "serviceType": {
        "const": "ABC"
      }
    }
  },
  "then": {
    "required": [ "parameters" ],
    "properties": {
      "parameters": {
        "properties": {
          "activityType": {
            "type": "string",
            "minLength": 10
        }
      }
    }
  },
  ...
}

存在“必需”关键字是因为如果该属性根本不存在,“if”子模式将验证为 true,这是您不想要的——您需要说“如果该属性存在,并且它的值为..., 然后 ...”。

第二个要求与第一个非常相似。您可以通过将它们包装在 allOf 中来同时在模式中使用多个“if”/“else”关键字:"allOf": [ { ..schema 1..}, { ..schema 2.. } ]


推荐阅读