根据父 属性 或父模式有条件地验证 json 模式
conditionally validate a json schema based on a parent property or parent schema
我有以下 json 架构
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"title": "MySchema",
"required": ["environment", "datacenter"],
"properties": {
"environment": {
"type": "string",
"title": "environment",
"enum": ["DEV", "STG", "PROD"]
},
"datacenter": {
"type": "object",
"title": "datacenter",
"properties": {
"value": {
"$ref": "#/definitions/datacenter"
}
}
}
},
"definitions": {
"datacenter": {
"type": "string",
"enum": [ "devDC1", "devDC2", "stgDC1", "stgDC2", "prodDC1", "prodDC2" ]
}
}
}
这是它的简单使用方法
{
"$schema": "http://localhost/schemas/v3/env.json",
"environment": "DEV",
"datacenter": {
"value": "devDC1"
}
}
我想做的是
如果环境设置为DEV,那么我应该只能select devDC1, devDC2作为datacenter属性的值,如果我select STG作为环境然后stgDC1 , stgDC2 是允许的,和 PROD
一样
请注意
"$ref": "#/definitions/datacenter"
在我的架构中实际上引用了另一个文件
可以使用if
+allOf
(见第二个例子here),例如:
"allOf": [
{
"if": {"properties": {"environment": {"const": "DEV"}}},
"then": {"properties": {"datacenter": {"properties": {"value": {"pattern": "^dev"}}}}}
},
{
"if": {"properties": {"environment": {"const": "STG"}}},
"then": {"properties": {"datacenter": {"properties": {"value": {"pattern": "^stg"}}}}}
},
{
"if": {"properties": {"environment": {"const": "PROD"}}},
"then": {"properties": {"datacenter": {"properties": {"value": {"pattern": "^prod"}}}}}
}
]
请注意,除此之外,您还需要将 "required": ["value"]
添加到 /properties/datacenter
中(否则无论环境如何,"datacenter": {}
也将被接受)。
我有以下 json 架构
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"title": "MySchema",
"required": ["environment", "datacenter"],
"properties": {
"environment": {
"type": "string",
"title": "environment",
"enum": ["DEV", "STG", "PROD"]
},
"datacenter": {
"type": "object",
"title": "datacenter",
"properties": {
"value": {
"$ref": "#/definitions/datacenter"
}
}
}
},
"definitions": {
"datacenter": {
"type": "string",
"enum": [ "devDC1", "devDC2", "stgDC1", "stgDC2", "prodDC1", "prodDC2" ]
}
}
}
这是它的简单使用方法
{
"$schema": "http://localhost/schemas/v3/env.json",
"environment": "DEV",
"datacenter": {
"value": "devDC1"
}
}
我想做的是
如果环境设置为DEV,那么我应该只能select devDC1, devDC2作为datacenter属性的值,如果我select STG作为环境然后stgDC1 , stgDC2 是允许的,和 PROD
一样请注意
"$ref": "#/definitions/datacenter"
在我的架构中实际上引用了另一个文件
可以使用if
+allOf
(见第二个例子here),例如:
"allOf": [
{
"if": {"properties": {"environment": {"const": "DEV"}}},
"then": {"properties": {"datacenter": {"properties": {"value": {"pattern": "^dev"}}}}}
},
{
"if": {"properties": {"environment": {"const": "STG"}}},
"then": {"properties": {"datacenter": {"properties": {"value": {"pattern": "^stg"}}}}}
},
{
"if": {"properties": {"environment": {"const": "PROD"}}},
"then": {"properties": {"datacenter": {"properties": {"value": {"pattern": "^prod"}}}}}
}
]
请注意,除此之外,您还需要将 "required": ["value"]
添加到 /properties/datacenter
中(否则无论环境如何,"datacenter": {}
也将被接受)。