JSON Schema 如何执行数组验证?

How in JSON Schema perform array validations?

我有以下 JSON 架构片段。

  "attributes": {
                "type": "array",
                "minItems": 3,
                "items": {
                    "type": "string",
                    "enum": [
                        "a",
                        "b",
                        "c"
                    ]
                }
            }

我想允许所有文件,这些文件在 "attributes" 数组中至少有 3 个元素。它们的值必须是 "a"、"b" 和 "c",但最重要的是我不想拒绝可能扩展该列表的文档。 例如,我希望以下代码段有效:

"attributes": ["x", "a", "b", "z", "c"]

目前我的验证失败,因为数组中还有其他值。

请指教

对于 draft-06,您可以使用关键字 contains:

{
  "type": "array",
  "minItems": 3,
  "allOf": [
    { "contains": { "const": "a" } },
    { "contains": { "const": "b" } },
    { "contains": { "const": "c" } }
  ]
}

对于 draft-04,您需要使用:

{
  "type": "array",
  "minItems": 3,
  "allOf": [
    { "not": { "items": { "not": { "enum": ["a"] } } } },
    { "not": { "items": { "not": { "enum": ["b"] } } } },
    { "not": { "items": { "not": { "enum": ["c"] } } } }
  ]
}

我找到了解决问题的方法:

"attributes": {
            "type": "array",
            "uniqueItems": true,
            "minItems": 3,
            "items": [
                {"type": "string", "enum": ["a"]},
                {"type": "string", "enum": ["b"]},
                {"type": "string", "enum": ["c"]}
            ]
        }

但是我不喜欢这种方法的地方是我必须按照它们在模式中的顺序指定所需的元素。 例如:"attributes": ["a", "b", "c", "z", "x"] 可以正常工作。但是如果我弄乱了必需属性的顺序,验证就会失败。 "attributes": ["b", "a", "c", "z", "x"] -- 无效的架构。 修复它也很好。