在JSON模式中定义枚举数组的正确方法


71

我想用JSON模式数组来描述,它应该包含零个或多个预定义值。为简单起见,让我们这些可能的值:onetwothree

正确的数组(应通过验证):

[]
["one", "one"]
["one", "three"]

不正确:

["four"]

现在,我知道"enum"应该使用该属性,但是找不到在哪里放置相关信息。

选项A(在下方"items"):

{
    "type": "array",
    "items": {
        "type": "string",
        "enum": ["one", "two", "three"]
    }
}

选项B:

{
    "type": "array",
    "items": {
        "type": "string"
    },
    "enum": ["one", "two", "three"]
}

1
Docs枚举值
KyleMit

Answers:


92

选项A正确且满足您的要求。

{
    "type": "array",
    "items": {
        "type": "string",
        "enum": ["one", "two", "three"]
    }
}

8

根据json-schema 文档,的枚举值array必须包含在"items"字段中:

{
    "type": "array",
    "items": {
        "type": "string",
        "enum": ["one", "two", "three"]
    }
}

如果您有一个array可以容纳例如不同类型项目的,则您的架构应类似于以下所示:

{
  "type": "array",
  "items": [
    {
      "type": "string",
      "enum": ["one", "two", "three"]
    },
    {
      "type": "integer",
      "enum": [1, 2, 3]
    }
  ]
}

第二个示例不允许数组包含两种不同的类型。它是元组验证[1],它约束数组中的第一和第二项以匹配“ items”数组中的第一和第二模式。[1] json-schema.org/understanding-json-schema/reference/...
格雷厄姆LEA

2
我认为在第二个例子中使用正确的结构大概是anyOfjson-schema.org/understanding-json-schema/reference/...
格雷厄姆LEA
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.