【问题标题】:JSON schema for validating list with different possible field values用于验证具有不同可能字段值的列表的 JSON 模式
【发布时间】:2020-08-23 09:29:06
【问题描述】:

在一个 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 只能包含类型为fooAlert1fooAlert2fooAlert3 的事件,不能包含其他类型的事件。 user_events 也是如此。所以,这个 JSON 不是是有效的:

{
    "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"
        }
      }
    }
  }
}

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

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

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

【问题讨论】:

    标签: json jsonschema


    【解决方案1】:

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

    您要问的是业务逻辑,与 JSON 数据的“形状”无关,这是 JSON Schema 的职责。

    您需要将此作为您的应用程序逻辑来实现。

    【讨论】:

      猜你喜欢
      • 2016-02-16
      • 2019-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      • 2017-06-19
      相关资源
      最近更新 更多