我想在json-schema中完成的任务:当属性 # docker rm guest
guest
为 # docker run -d --name newguest -p 8080:80 mymod/httpd:v1 /usr/sbin/httpd -D FOREGROUND
7afbbefec5191f632e149f85ae10ed0ba88f1c545daad18cb930e575ef6a3e63
时,应该需要某些其他属性。 enabled
时,应禁止这些属性。
这是我的json-schema:
true
使用false
版本6.5进行验证,无论{
"type": "object",
"properties": {
"enabled": { "type": "boolean" }
},
"required" : ["enabled"],
"additionalProperties" : false,
"if": {
"properties": {
"enabled": true
}
},
"then": {
"properties": {
"description" : { "type" : "string" },
"count": { "type": "number" }
},
"required" : ["description", "count"]
}
}
的值如何,都需要ajv
等。例如,对于数据:
count
我的验证错误是:
enabled
如何使用json-schema { "enabled": false }
完成此操作?
请注意,这个问题类似于,但要求比以下更严格:
jsonSchema attribute conditionally required
答案 0 :(得分:2)
尝试此架构:
{
"type": "object",
"properties": {
"enabled": {
"type": "boolean"
}
},
"required": [
"enabled"
],
"if": {
"properties": {
"enabled": {
"const": true
}
}
},
"then": {
"properties": {
"enabled": {
"type": "boolean"
},
"description": {
"type": "string"
},
"count": {
"type": "number"
},
"additionalProperties": false
},
"required": [
"description",
"count"
]
},
"else": {
"properties": {
"enabled": {
"type": "boolean"
}
},
"additionalProperties": false
}
}
如果您需要"additionalProperties": false
,则必须枚举then
和else
中的所有属性。如果您可以接受其他属性,则架构可以更简单:
{
"type": "object",
"properties": {
"enabled": {
"type": "boolean"
}
},
"required": [
"enabled"
],
"if": {
"properties": {
"enabled": {
"const": true
}
}
},
"then": {
"properties": {
"description": {
"type": "string"
},
"count": {
"type": "number"
}
},
"required": [
"description",
"count"
]
}
}
我查看了ajv
cli。
有效:{"enabled": false}
无效:{"enabled": true}
有效:{"enabled": true, "description":"hi", "count":1}
答案 1 :(得分:1)
这受到了vearutop的出色答案的启发。我认为它可能会更短一点,并完成我声明的目的。
{
"type": "object",
"oneOf" : [
{
"properties": {
"enabled": { "const": false }
},
"required": ["enabled"],
"additionalProperties": false
},
{
"properties": {
"enabled": { "const": true },
"description": { "type": "string" },
"count": { "type": "number" }
},
"required": [ "enabled", "description", "count"],
"additionalProperties": false
}
]
}
正如评论中所指出的,这是this answer中详述的 Enum 策略的特定变体。
答案 2 :(得分:1)
要实现这一点,在if
语句中您需要使用const
关键字,因此架构将如下所示:
{
"type": "object",
"properties": {
"enabled": { "type": "boolean" }
},
"required" : ["enabled"],
"additionalProperties" : false,
"if": {
"properties": {
"enabled": {"const": true}
}
},
"then": {
"properties": {
"description" : { "type" : "string" },
"count": { "type": "number" }
},
"required" : ["description", "count"]
}
}