json - 用于验证具有不同可能字段值的列表的 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无效:fooAlert2
fooAlert3
user_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 定义不同的event
s,但这意味着我必须定义潜在的几十个列表和事件。
有没有更简单的说法,我想验证列表中event
的对象alert_events
可以有一组type
s,而另一个列表可以有另一组类型?
解决方案
您不能在验证中引用和使用实例数据作为值。
您要问的是业务逻辑,而不是与 JSON 数据的“形状”有关,这是 JSON Schema 的职权范围。
您需要将其实现为您的应用程序逻辑。
推荐阅读
- react-native - 如何导航到堆栈顶部(在 react-navigation-v5/6 上)?
- javascript - XSS 保护 HTML 实体
- android - 在颤振应用程序中添加时间选择器的正确方法是什么?
- laravel - 使用 foreach 更新 Laravel 错误:语法错误,意外 ' ' (T_STRING),期待 ']'
- laravel - 如何为会话驱动程序选择警卫
- python - Atom [Linter] Error running Flake8 Error: spawn EACCES
- reactjs - 与传递属性相比,useContext/useSelector 会影响性能吗?
- c# - 带卷曲的 WebDav
- javascript - 是否有删除firestore集合及其中所有文档的功能,如deleteDocument()?
- c# - 如何在字符串后删除一定数量的文本?