为什么 JSON Schema maximum 在 allOf 中不起作用?

Why does JSON Schema maximum not work in allOf?

给定以下 JSON 架构:

{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "properties": {
    "pageA": {
      "properties": {
        "a": { "type": "number" },
      },
      "allOf": [
        {
          "if": {
            "properties": {
              "a": { "maximum": 10 }
            }
          },
          "then": {
            "properties": {
              "b": { "type": "number" },
              "c": { "type": "string" }
            }
          },
          "else": {
            "allOf": [
              {
                "if": {
                  "properties": {
                    "a": { "maximum": 20 }
                  }
                },
                "then": {
                  "properties": {
                    "e": { "type": "number" },
                    "f": { "type": "string" }
                  }
                },
                "else": {
                  "allOf": [
                    {
                      "if": {
                        "properties": {
                          "a": { "maxiumum": 30 }
                        }
                      },
                      "then": {
                        "properties": {
                          "i": { "type": "number" },
                          "j": { "type": "string" }
                        }
                      },
                      "else": {
                        "properties": {
                          "k": { "type": "number" },
                          "l": { "type": "string" }
                        }
                      }
                    }
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  }
}

我预计:

{
    "pageA": {
      "a": 31,
      "k": "50"
    }
}

生成“无效类型。需要数字但得到的是字符串。”但它是有效的。我知道 allOf 中嵌套的任何属性都无法被 additionalProperties 捕捉到,而且验证似乎也以类似的方式应用。

您的架构有两个问题。第一个解决起来超级简单。打字错误(我们都犯过)。

"a": { "maxiumum": 30 } 应该读作 maximum

现在让我们看一下规范,看看 maximum 做了什么...

The value of "maximum" MUST be a number, representing an inclusive upper limit for a numeric instance.

If the instance is a number, then this keyword validates only if the instance is less than or exactly equal to "maximum".

https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.6.2.2

鉴于 30 正好等于 30,您触发了 then 子句而不是 else 子句。

如果您希望该值是独占的,还有另一个关键字...exclusiveMaximum,它就是这样做的。

您可以在此处看到实际效果:https://jsonschema.dev/s/8Yi6e