Json 架构检查所有项目枚举是否存在于对象数组中

Json schema check all items enum are present in array of objects

我有这样的 json 架构:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "country": {
        "type": "string",
        "maxLength": 2,
        "enum": ["aa", "bb"]
      }
    },
    "required": [
      "country"
    ]
  }
}

和 json 这种格式:

[
  {"country": "aa"},
]

我希望架构检查 json 文件是否包含枚举中列出的所有国家/地区:

[
  {"country": "aa"},
  {"country": "bb"},
]

可能吗?

您可以使用 v5/6 包含关键字:

{
  "allOf": [
    { "contains": { "properties": { "country": { "constant": "aa" } } } },
    { "contains": { "properties": { "country": { "constant": "bb" } } } }
  ]
}

"constant": "aa" 是另一个 v5/6 关键字,与 "enum": ["aa"] 相同。 目前Ajv支持这些关键字(有点自我推销)。

对于那些不能使用@esp 便捷语法的人,这里有一个旧式的解决方案:

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "array",
    "items": {
        "type": "object",
        "properties": {
            "country": {
                "type": "string",
                "maxLength": 2,
                "enum": ["aa", "bb"]
            }
        },
        "required": [
            "country"
        ]
    },
    "allOf": [
        {"not": {"items": {"not": {"properties": {"country": {"enum": ["aa"]}}}}}},
        {"not": {"items": {"not": {"properties": {"country": {"enum": ["bb"]}}}}}}
    ]
}