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

时间:2018-10-29 08:23:40

标签: python enums jsonschema

通过下面的示例问题将更加清楚:

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

它包括booleanstring类型。它可以工作,但是我想将字符串部分限制为enums的列表:

["off", "on", "semi-on"]

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

下面没有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
}

1 个答案:

答案 0 :(得分:1)

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的{​​{1}}将无法通过true验证,因为enum不包含在枚举中。

true