json - 如何通知 Json 模式它必须在其数组中至少具有一种类型的对象,但其他类型是可选的
问题描述
我正在为工作更新 JSON 模式。
对于 json 数组,我们有
"accountsInfo": [{
"type":"ADMIN",
"firstName":"Bill",
"lastName":"Cipher",
"emailAddress":"bcipher@gfalls.com"
}, {
"type":"USER"
"firstName":"Bugs",
"lastName":"Bunny",
"emailAddress":"whats@updoc.org"
}]
USER 类型对于此模式必须是可选的,数组中至少需要 1 个 ADMIN 类型。我怎样才能做到这一点?
这是架构文件的一部分。它使用 Json Schema 7。
"accountsInfo": {
"type": "array",
"uniqueItems": true,
"minItems": 2,
"items": [
{
"type": "object",
"required": [
"type",
"firstName",
"lastName",
"emailAddress"
],
"properties": {
"type": {
"type": "string",
"enum": [
"ADMIN",
"USER"
]
},
"firstName": {
"type": "string",
"$ref": "#/definitions/non-empty-string"
},
"lastName": {
"type": "string",
"$ref": "#/definitions/non-empty-string"
},
"emailAddress": {
"type": "string",
"format": "email"
}
}
}
]
}
解决方案
您可以为此使用“包含”关键字。在伪代码中:“数组必须包含(至少一个)成功评估此模式的项目”。
作为 and 的兄弟关键字"type": "object"
,"items": { ... }
添加:
"contains": {
"properties": {
"type": {
"const": "ADMIN"
}
}
}
此外,您的"items"
关键字中有一个错误:如果您打算让该子模式匹配所有项目,而不仅仅是第一个项目,请删除模式周围的额外数组。“items”的数组形式依次将数据中的每一项与架构中的每一项进行匹配,并且您只需为第一项指定架构,因此第一项之后的所有项都可以是任何内容。
"items": { .. schema .. }
不是"items": [ { .. schema .. } ]
。
推荐阅读
- c - 几乎完成十进制到任何基本转换功能,不知道如何实现十六进制转换
- r - 添加新列替换字符串作为值
- matlab - 在噪声信号中找到模型函数的稳健拟合
- spring-boot - 两个代码(Spring Boot)有什么区别?
- javascript - 反应多选下拉
- laravel - 如何使用 Laravel 按 ID 删除 Google Sheet 中的行
- eclipse - 无法在 Eclipse 上安装 Sonarlint
- microservices - 每服务表和每服务模式有什么区别?
- postgresql - 如何优化这个 PostgreSQL 查询?
- javascript - 如何解析通过 Report-To 标头端点报告的 NEL(网络错误日志记录)错误?