JSON 模式验证器 - 根据模式不同部分中的另一个属性验证一个属性

时间:2021-04-24 06:47:52

标签: json jsonschema json-schema-validator ajv

我有一个开放的 api 模式,我想在其中验证

  1. 如果 oauth2 部分中的 components 流包含 tokenUrl 格式的 string,那么 url 部分中的 servers 应该具有 { {1}} 在 url 值中。
  2. 如果 https: 不存在,那么它什么都不做

JSON 模式验证器有什么办法可以做到这一点吗?

以下是供参考的架构

tokenUrl

1 个答案:

答案 0 :(得分:0)

我找到了一种方法来实现这种类型的验证。下面是帮助您验证相同的架构

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "servers": {},
    "components": {}
  },
  "if": {
    "properties": {
      "components": {
        "properties": {
          "securitySchemes": {
            "type": "object",
            "patternProperties": {
              "^[a-zA-Z0-9\\.\\-_]+$": {
                "type": "object",
                "properties": {
                  "flows": {
                    "type": "object",
                    "properties": {
                      "tokenUrl": {
                        "const": true
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  "then": {
    "type": "object",
    "properties": {
      "servers": {
        "items": {
          "type": "object",
          "properties": {
            "url": {
              "type": "string",
              "pattern": "https://"
            }
          }
        }
      }
    }
  }
}

if - then 用于设置组件 tokenUrl 属性和服务器 url 属性之间的条件关系。这里

{
    "tokenUrl": {
        "const": true
    }
}

表示 tokenUrl 应该出现在 components 对象中,那么 then 块中定义的任何规则都会生效。下面的架构将验证 url 模式为仅 https

{
    "url": {
        "type": "string",
        "pattern": "https://"
    }
}
相关问题