当存在 属性 时,在 json 模式中添加模式验证

Add pattern validation in json schema when property is present

下面是我的架构定义,我想添加依赖于环境属性名称(env1、env2 或 env3)的模式。每个环境应该有不同的模式。例如,当存在 env1 时,url 将具有与存在 env2 时不同的模式等

{
  "environments": {
    "env1": {
      "defaultAccess": {
        "url": [
          "something-staging"
        ]
      }
    }
  }
}

我当前对该示例的模式定义

    {
    "$schema": "https://json-schema.org/draft-07/schema#",
    "definitions": {
        "envType": {
            "type": "object",
            "properties": {

                "defaultAccess": {
                    "type": "object",
                    "properties": {
                        "url": {
                            "type": "string",
                            "pattern": "^[a-zA-Z0-9- \/]*$"

                        }
                    },
                    "required": [
                        "url"
                    ]
                }
            }
        },
        "environmentTypes": {
            "type": "object",
            "properties": {
                "env1": {
                    "$ref": "#/definitions/envType"

                },
                "env2": {
                    "$ref": "#/definitions/envType"
                },
                "env3": {
                    "$ref": "#/definitions/envType"
                }
            }
        },

        "type": "object",
        "properties": {
            "environments": {
                "$ref": "#/definitions/environmentTypes"
            }
        }
    }
}

我脑子里有这样的东西,但不知道如何正确地将它应用到架构中。

{
      "if": {
        "properties": {
          "environments": {
            "env1" : {}
          }
        }
      },
      "then":{
        "properties": {
          "environments-env1-defaultAccess-url" : { "pattern": "^((?!-env2).)*$" }
        }
      }
    }

等..

如果正确理解了您要执行的操作,则此类操作不需要条件句。

您的架构中有一个错误可能会误导您。您在 definitions 关键字中有主模式。如果你通过验证器 运行 this,你应该得到一个错误,指出值 a /definitions/type 必须是一个对象。

除此之外,使用 allOf 的架构组合应该可以解决问题。下面,我在 /definitions/env1Type.

展示了一个例子

您似乎希望以一种不那么冗长的方式来指定对象结构深处的模式 ("")。不幸的是,没有办法像我在 /definitions/env1Type.

中演示的那样一直将 properties 关键字链接起来
{
  "$schema": "https://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "environments": { "$ref": "#/definitions/environmentTypes" }
  },
  "definitions": {
    "environmentTypes": {
      "type": "object",
      "properties": {
        "env1": { "$ref": "#/definitions/env1Type" },
        "env2": { "$ref": "#/definitions/env2Type" },
        "env3": { "$ref": "#/definitions/env3Type" }
      }
    },
    "envType": { ... },
    "env1Type": {
      "allOf": [{ "$ref": "#/definitions/envType" }],
      "properties": {
        "defaultAccess": {
          "properties": {
            "url": { "pattern": "^((?!-env1).)*$" }
          }
        }
      }
    },
    "env2Type": { ... },
    "env3Type": { ... }
  }
}