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

JSON schema validator - validate one property based on another property in different part of schema

我打开了 api 模式,我想在其中验证

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

有什么方法可以使用 JSON 模式验证器吗?

下图供参考

{  
    "servers": [
        {
            "url": "http://my.api.server.com/",
            "description": "API server"
        }
    ], 
    "components": {
        "securitySchemes": {
            "OAuth2": {
                "type": "oauth2",
                "flows": {
                    "authorizationCode": {
                        "scopes": {
                            "write": "modify objects in your account",
                            "read": "read objects in your account"
                        },
                        "authorizationUrl": "https://example.com/oauth/authorize",
                        "tokenUrl": "https://example.com/oauth/token" 
                    }
                }
            }
        }
    },
    "security": [
        {
        "OAuth2": [
                "write",
                "read"
            ]
        }
    ]
}

我找到了实现此类验证的方法。以下是帮助您验证相同内容的架构

{
  "$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://"
    }
}