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

sen*_*asi 49 arrays enums json jsonschema

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

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

[]
["one", "one"]
["one", "three"]
Run Code Online (Sandbox Code Playgroud)

不正确:

["four"]
Run Code Online (Sandbox Code Playgroud)

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

选项A(下"items"):

{
    "type": "array",
    "items": {
        "type": "string",
        "enum": ["one", "two", "three"]
    }
}
Run Code Online (Sandbox Code Playgroud)

选项B:

{
    "type": "array",
    "items": {
        "type": "string"
    },
    "enum": ["one", "two", "three"]
}
Run Code Online (Sandbox Code Playgroud)

jru*_*ren 67

选项A是正确的,并满足您的要求.

{
    "type": "array",
    "items": {
        "type": "string",
        "enum": ["one", "two", "three"]
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 您可以省略 `"type": "string"`。Emum “按原样”应用值,因此无需定义类型 (2认同)

Gio*_*ous 8

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

{
    "type": "array",
    "items": {
        "type": "string",
        "enum": ["one", "two", "three"]
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您有一个array可以容纳不同类型的项目,那么您的架构应该如下所示:

{
  "type": "array",
  "items": [
    {
      "type": "string",
      "enum": ["one", "two", "three"]
    },
    {
      "type": "integer",
      "enum": [1, 2, 3]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

  • 第二个示例不允许数组包含两种不同的类型。它是元组验证[1],它约束数组中的第一个和第二个项目以匹配“items”数组中的第一个和第二个模式。[1] https://json-schema.org/understanding-json-schema/reference/array.html#tuple-validation (3认同)
  • 我认为在第二个示例中使用的正确构造可能是“anyOf”:https://json-schema.org/understanding-json-schema/reference/combining.html#anyof (3认同)