条件格式未在 JSONSchema 中评估
Conditional formatting not evaluated in JSONSchema
我正在尝试验证 JSON 中表示的防火墙规则。
给出我的 JSONSchema 的最小示例如下:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Example",
"type": "object",
"properties": {
"from": {
"$ref": "#/definitions/addressGroup"
},
"action": {
"type": "string",
"enum": ["binat", "pass"]
}
},
"allOf": [
{
"if": {
"properties": {
"action": {
"const": "binat"
}
}
},
"then": {
"properties": {
"from": {
"format": "ip-address"
}
}
}
}
],
"additionalProperties": false,
"required": [
"from",
"action"
],
"definitions": {
"addressGroup": {
"type": "string",
"pattern": "^[ !<a-zA-Z].+$"
}
}
}
以下 JSON 通过验证:
{
"action": "pass",
"from": "test"
}
但是对于这个 JSON,“发件人”字段是根据 addressGroup
而不是 "format": "ip-address"
.
进行评估的
{
"action": "binat",
"from": "10.1.1.1"
}
我希望触发“then”子句并根据“ip-address”定义强制格式化“from”字段。
可在此处找到最小演示:https://www.jsonschemavalidator.net/s/EsQVoaXw
我忽略了什么?
对于 draft-07,IP 地址的指定格式为 ipv4
或 ipv6
https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-7.3.4
此外,format
默认情况下什么都不做,必须启用它。
这已在 2019-09 草案中进一步阐明,并在 2020-12 草案中针对可预测行为进行了正式化。
您可能必须在您的实施中启用它。我不确定 jsonschemavalidator.net 的作用,因为它不是开源的。 jsonschema.dev 没有启用基于 format
的验证。
您已正确使用 if/then
,但您的架构中的 addressGroup
仍将应用(不清楚这是否是您的意图)。
根据您的评论更新:
要仅在 if
模式失败时应用 addressGroup
,您需要使用 else
关键字(if / then / else 逻辑),将 properties.form
移动到那里.
{
"if": false,
"then": {},
"else": {
"properties": {
"from": {
"$ref": "#/definitions/addressGroup"
}
}
}
...
}
我正在尝试验证 JSON 中表示的防火墙规则。
给出我的 JSONSchema 的最小示例如下:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Example",
"type": "object",
"properties": {
"from": {
"$ref": "#/definitions/addressGroup"
},
"action": {
"type": "string",
"enum": ["binat", "pass"]
}
},
"allOf": [
{
"if": {
"properties": {
"action": {
"const": "binat"
}
}
},
"then": {
"properties": {
"from": {
"format": "ip-address"
}
}
}
}
],
"additionalProperties": false,
"required": [
"from",
"action"
],
"definitions": {
"addressGroup": {
"type": "string",
"pattern": "^[ !<a-zA-Z].+$"
}
}
}
以下 JSON 通过验证:
{
"action": "pass",
"from": "test"
}
但是对于这个 JSON,“发件人”字段是根据 addressGroup
而不是 "format": "ip-address"
.
{
"action": "binat",
"from": "10.1.1.1"
}
我希望触发“then”子句并根据“ip-address”定义强制格式化“from”字段。
可在此处找到最小演示:https://www.jsonschemavalidator.net/s/EsQVoaXw
我忽略了什么?
对于 draft-07,IP 地址的指定格式为 ipv4
或 ipv6
https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-7.3.4
此外,format
默认情况下什么都不做,必须启用它。
这已在 2019-09 草案中进一步阐明,并在 2020-12 草案中针对可预测行为进行了正式化。
您可能必须在您的实施中启用它。我不确定 jsonschemavalidator.net 的作用,因为它不是开源的。 jsonschema.dev 没有启用基于 format
的验证。
您已正确使用 if/then
,但您的架构中的 addressGroup
仍将应用(不清楚这是否是您的意图)。
根据您的评论更新:
要仅在 if
模式失败时应用 addressGroup
,您需要使用 else
关键字(if / then / else 逻辑),将 properties.form
移动到那里.
{
"if": false,
"then": {},
"else": {
"properties": {
"from": {
"$ref": "#/definitions/addressGroup"
}
}
}
...
}