通过下面的示例问题将更加清楚:
data = {"type": "object", "properties": {"product": {"type": ["boolean","string"]}}}
它包括boolean
和string
类型。它可以工作,但是我想将字符串部分限制为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
}
答案 0 :(得分:1)
JSON模式定义了验证关键字,这些验证关键字按其将如何应用于实例的方式进行了细分。
enum
在Validation Keywords for Any Instance Type部分下。
这意味着它适用于任何实例类型,包括布尔值。
因此,您必须在有效值枚举中包含布尔值true
和false
。 (在此示例中,这确实使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