Correct way to define array of enums in JSON schema

99封情书 提交于 2019-12-09 14:00:12

问题


I want to describe with JSON schema array, which should consist of zero or more predefined values. To make it simple, let's have these possible values: one, two and three.

Correct arrays (should pass validation):

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

Incorrect:

["four"]

Now, I know the "enum" property should be used, but I can't find relevant information where to put it.

Option A (under "items"):

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

Option B:

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

回答1:


Option A is correct and satisfy your requirements.

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



回答2:


According to the json-schema documentation, the enumerated values of an array must be included in the "items" field:

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

If you have an array that can hold e.g. items of different type, then your schema should look like the one below:

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


来源:https://stackoverflow.com/questions/30924271/correct-way-to-define-array-of-enums-in-json-schema

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!