node.js - 有没有办法基于同级属性在 jsonschema 中创建枚举?
问题描述
描述
我有一个带有两个属性(除其他外)的 JSON 对象,即category
和subcategory
,我有一个函数来获取类别列表,另一个函数来获取给定类别的子类别。
所以我的架构看起来像这样:
{
"type": "array",
"items": {
"type": "obect",
"properties": {
"category": {
"type": "string",
"enum": getCategories()
},
"subcategory": {
"type": "string",
"enum": getSubcategories(category)
}
}
}
注意:一个子类别只属于一个主要类别
问题
类别列表很大,我想用 json 模式检查类别和子类别是否有效,所以我想知道是否有办法这样做。
为节点 js使用npm 包
例子:
假设我有类别 A 和 B[A1,A2]
和[B1,B2]
,如果要验证的 json 有类别 AI 想要检查子类别[A1,A2]
不在[A1,A2,B1,B2]
我试过的
尝试了其他帖子中的 if-else 语句,但正如我所提到的,列表很大,看起来根本不是一个好习惯
解决方案
目前,需要if
/then
构造来根据类别指定子类别值:
{
"type": "array",
"items": {
"type": "object",
"properties": {
"category": {
"type": "string",
"enum": [ ... ]
},
"subcategory": {
"type": "string",
},
},
"allOf": [
{
"if": {
"properties": {
"category": { "const": "option1" },
}
},
"then": {
"properties": {
"subcategory": {
"enum": [ ... ]
}
}
}
},
{
"if": {
"properties": {
"category": { "const": "option2" },
}
},
"then": {
"properties": {
"subcategory": {
"enum": [ ... ]
}
}
}
},
{ ... }
]
}
}
但是,有人提议为下一个规范草案添加一个新关键字,这将大大缩短语法:https ://github.com/json-schema-org/json-schema-spec/issues/1082
推荐阅读
- windows - Docker + Windows 容器:使用 PowerShell 的最佳实践
- javascript - 图像之间的响应虚线
- javascript - 使用实时加速度数据使用 jquery 和 css 为汽车制作动画
- tensorflow - 在人类活动识别中使用迁移学习训练时间流
- .net - 发送到 IAsyncEnumerable 的 `Stream` 的实现
- python-3.x - 为什么比较列表时列表索引超出范围,但打印时却没有?
- python - 将带有滞后功能的查询转换为带有烧瓶的 sqlalchemy?
- javascript - 在 React Native 中卸载组件期间,清理功能在 UseEffect Hook 中不起作用
- pentaho - 删除字符串 pentaho 前面的特殊字符
- angular - 值未在 Angular 中发布到 Nodejs API