首页 > 解决方案 > 用于验证具有不同可能字段值的列表的 JSON 模式

问题描述

在 JSON 结构(“事件包”)中,我收集了几个事件列表。这些称为事件列表。该列表中的每个事件至少有一个type字段,其值取决于它存储在哪个列表中。考虑以下有效示例:

{
    "event_bundle": {
        "alert_events": [
            { "type": "fooAlert1", "value": "bar" },
            { "type": "fooAlert2", "value": "bar" },
            { "type": "fooAlert3", "value": "bar" }
        ],
        "user_events": [
            { "type": "fooUser1", "value": "bar" },
            { "type": "fooUser2", "value": "bar" },
            { "type": "fooUser3", "value": "bar" }
        ]
    }
}

在这里,alert_events只能包含类型为和的事件fooAlert1,不能包含其他类型的事件。也是如此。因此,此 JSON无效fooAlert2fooAlert3user_events

{
    "event_bundle": {
        "alert_events": [
            { "type": "fooAlert1", "value": "bar" },
            { "type": "fooUser2", "value": "bar" },
            { "type": "foo", "value": "bar" }
        ],
        "user_events": [
            { "type": "fooAlert1", "value": "bar" },
            { "type": "fooUser2", "value": "bar" },
            { "type": "foo", "value": "bar" }
        ]
    }
}

这是无效的,因为fooUser2不能出现在alert_events列表中的事件中,fooAlert1也不能出现在user_events. 此外,该事件foo根本无效。

我目前有以下简单的架构:

{
  "type": "object",
  "definitions": {
    "event_list": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/event"
      }
    },
    "event": {
      "type": "object",
      "required": ["type", "value"],
      "properties": {
        "type": { "type": "string" },
        "value": { "type": ["string", "object"] },
        "source": { "type": ["string", "null"] }
      }
    }
  },
  "properties": {
    "event_bundle": {
      "type": "object",
      "properties": {
        "alert_events": {
          "$ref": "#/definitions/event_list"
        },
        "user_events": {
          "$ref": "#/definitions/event_list"
        }
      }
    }
  }
}

但是,这并不能完全验证允许type的 s。

我知道我可以event_list用不同的 s 定义不同的events,但这意味着我必须定义潜在的几十个列表和事件。

有没有更简单的说法,我想验证列表中event的对象alert_events可以有一组types,而另一个列表可以有另一组类型?

标签: jsonjsonschema

解决方案


您不能在验证中引用和使用实例数据作为值。

您要问的是业务逻辑,而不是与 JSON 数据的“形状”有关,这是 JSON Schema 的职权范围。

您需要将其实现为您的应用程序逻辑。


推荐阅读