问题描述
下面是我的架构定义,我想添加依赖于环境propertyName(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
关键字中。如果通过验证程序运行此操作,则会收到一条错误消息,说明值/definitions/type
必须是一个对象。
除此之外,使用allOf
进行模式组合应该可以解决问题。下面,我在/definitions/env1Type
处显示了一个示例。
您似乎希望以一种更简单的方式在对象结构(""
)中指定模式。不幸的是,就像我在properties
上所演示的那样,完全没有必要将/definitions/env1Type
关键字一直向下链接。
{
"$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": { ... }
}
}