jsonschema - 如何使用 JSON Schema 按类型限制数组中的最大项目数?
问题描述
我有一个数组类型的 json-schema (draft-07) 来存储多种类型的数据,例如
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "array",
"items": {
"type": "object",
"required": [
"type",
"data"
],
"additionalProperties": false,
"properties": {
"type": {
"type": "string",
"enum": [
"banner_images",
"description_box",
"button"
]
},
"data": {
"type": "object"
}
},
"allOf": [
{
"if": {
"properties": {
"type": {
"const": "banner_images"
}
}
},
"then": {
"properties": {
"data": {
"$ref": "components/banner_images.json"
}
}
}
},
{
"if": {
"properties": {
"type": {
"const": "description_box"
}
}
},
"then": {
"properties": {
"data": {
"$ref": "components/description_box.json"
}
}
}
},
{
"if": {
"properties": {
"type": {
"const": "button"
}
}
},
"then": {
"properties": {
"data": {
"$ref": "components/button.json"
}
}
}
}
]
}
}
验证以下数据
[
{
"type": "banner_images",
"data": {
"images": [
{
"url": "https://example.com/image.jpg"
}
]
}
},
{
"type": "description_box",
"data": {
"text": "Description box text"
}
},
{
"type": "button",
"data": {
"label": "Click here",
"color": {
"label": "#ff000ff",
"button": "#00ff00",
"border": "#00ff00"
},
"link": "https://example.com"
}
}
]
到目前为止,用户可以提供来自banner_images
、description_box
和的任意数量的组件button
。
我想根据组件类型限制每个组件
- 横幅图像-> 1
- 描述框-> 5
- 按钮 -> 10
有一个选项可以设置数组类型中项目的长度https://json-schema.org/understanding-json-schema/reference/array.html#id7
但是如何根据类型限制项目的长度?
解决方案
您可以通过组合“contains”和“maxContains”来做到这一点(请注意,这需要支持草稿版本 2019-09 或更高版本的实现。)
在伪代码中: components 数组包含包含具有属性“type”的对象的项目。当“type”为“banner_images”时,最多可以存在1个这样的项目。当“type”为“description_box”时,最多可以存在5个这样的item。当“type”为“button”时,最多可以有10个这样的item。
那是:
"items": {
"type": "object",
...
},
"allOf": [
{
"contains": {
"properties": {
"type": {
"const": "banner_images"
}
}
},
"minContains": 0,
"maxContains": 1
},
{
"contains": {
"properties": {
"type": {
"const": "description_box"
}
}
},
"minContains": 0,
"maxContains": 5
},
{
"contains": {
"properties": {
"type": {
"const": "button"
}
}
},
"minContains": 0,
"maxContains": 10
},
]
推荐阅读
- c# - IMongoCollection
当我传入 Func 的谓词时抛出 - java - 如何在 eclipse.ini 中设置 -Dorg.eclipse.swt.browser.IEVersion=12001 属性打开 Microsoft Edge 20?
- javascript - 如果 ReplaySubject 没有在 RXJS 中发出任何值,则startsWith 运算符
- r - R,将分组列作为字符串传递以汇总函数参数
- ios - tableView(_:cellForRowAt:) 崩溃
- javascript - 使用 javascript "onload" 启动 SVG 动画
- swift - 使用 SwiftUI 和 AVFoundation 捕获视频
- java - 图像出 JFrame 但同时在 JFrame 上
- objective-c - 从命令行编译时将 SDK 版本写入二进制文件 (macOS)
- java - 如何使用 Mockito 验证带有 ByteBuffer 参数的调用?