如何在枚举中包含 Jsonschema 多类型参数?

How to include Jsonschema multiple type parameter with enum?

通过下面的例子问题会更清楚:

data = {"type": "object", "properties": {"product": {"type": ["boolean","string"]}}}

它包括booleanstring两种类型。它有效,但我想将字符串部分限制为 enums:

的列表
["off", "on", "semi-on"]

type 不是 list 时,它可以工作,但是当我将其作为列表时,我无法为 string 类型提供 enum

下面没有 boolean 的例子也可以:

data = {"type": "object", "properties": {"product": {"type": "string", "enum": ["off", "on", "semi-on"]}}}

应该拆分架构,还是有其他方法?


EDIT-1: 真正的架构如下:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {
        "is_trusted": {"type": "boolean"},
        "is_active": {"type": "boolean"},
        "addresses": {"type": "array"},
        "attachments": {
            "type": "object",
            "properties": {
                "send_web_push": {"type": "boolean"},
                "receive_web_push": {"type": "boolean"}
            },
            "required": ["send_web_push", "receive_web_push"],
            "additionalProperties": false
        }
    },
    "required": ["is_trusted", "is_active", "addresses"],
    "additionalProperties": false
}

JSON 架构定义了验证关键字,这些关键字按它们将如何应用于实例进行划分。

enumValidation Keywords for Any Instance Type 部分下。

这意味着它适用于任何实例类型,包括布尔值。

因此,您必须在有效值枚举中包含布尔值 truefalse。 (在这个例子中,这确实使 type 变得多余)。

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "product": {
      "type": [
        "boolean",
        "string"
      ],
      "enum": [
        "off",
        "on",
        "semi-on",
        true,
        false
      ]
    }
  }
}

以下实例现在对上述架构有效。 在您的第一个架构中,product 的值为 true 将无法通过 enum 验证,因为 true 未包含在枚举中。

{
  "product": true
}