【问题标题】:How to perform length check validation under certain conditions using Json Schema Validator?如何使用 Json Schema Validator 在特定条件下执行长度检查验证?
【发布时间】:2021-09-03 07:55:04
【问题描述】:

我的 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 不应为 null,且最小长度必须为 20。

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

谁能帮我语法?有可能吗?

【问题讨论】:

标签: json jsonschema


【解决方案1】:

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

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

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

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

【讨论】:

  • 感谢您的回答。有用。有没有办法指定自定义错误消息来解释缺少哪些属性。目前从错误信息中看不清楚?
  • 可能;您必须检查您正在使用的评估器的文档。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-18
  • 2019-04-21
  • 1970-01-01
  • 2021-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多