JSON 架构 - 枚举或对象

JSON Schema - Enum or object

我正在尝试编写一个架构来验证以下内容。

对象 Foo 可以有任意数量的属性,这些属性必须是枚举或 Foo 的另一个实例。

例如假设枚举值是 A 或 B,一个有效的对象可能看起来像。

{
  "test": "A",
  "test1": "B",
  "test2": {
    "test4": "A",
    "test5": {
      "test6": "B"
    }
  }
}

编辑:

一个更好更短的自引用模式,你可以试试online

anyOf优于oneOf,因为oneOf需要针对所有项进行验证以确保只有一个pass,但是anyOf可以在first之后停止通过跳过其他项目。

{
  "anyOf": [
    {
      "enum": ["A", "B"]
    },
    {
      "type": "object",
      "additionalProperties": {
        "$ref": "#"
      }
    }
  ]
}

anyOf 需要在根级别解决 JSON 架构限制 $ref 忽略所有同级关键字。

已与 ajv cli

核实
{
  "anyOf": [
    {"$ref": "#/definitions/Foo"}
  ],
  "definitions": {
    "Foo": {
      "oneOf": [
        {
          "enum": ["A", "B"]
        },
        {
          "type": "object",
          "additionalProperties": {
            "$ref": "#/definitions/Foo"
          }
        }
      ]
    }
  }
}