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

htzpubme  于 2023-11-20  发布在  其他
关注(0)|答案(2)|浏览(163)

我想用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"]
}

ev7lccsx

ev7lccsx1#

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

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

字符串
更新20231108:type可以省略。根据最新的json-schema规范,The enum keyword is used to restrict a value to a fixed set of values. It must be an array with at least one element, where each element is unique.You can use enum even without a type, to accept values of different types.

idv4meu8

idv4meu82#

根据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]
    }
  ]
}

相关问题