json - JSON Schema if/then 需要嵌套对象
问题描述
我有一个 JSON:
{
"i0": {
"j0": {
"a0": true
}
},
"i1": {
"j1": {
"a1": "stuff"
}
}
}
我想要一个验证:如果a0
是真的,a1
应该是必需的。
我的架构目前是:
{
"$schema": "http://json-schema.org/draft-07/schema",
"id": "id",
"type": "object",
"required": [
"i0",
"i1"
],
"allOf": [
{
"if": {
"properties": {
"i0": {
"j0": {
"a0": true
}
}
}
},
"then": {
"properties": {
"i1": {
"j1": {
"required": [
"a1"
]
}
}
}
}
}
]
}
这个条件似乎实际上并没有运行。required
或者,如果我尝试将其置于与我正在检查的值相同的水平上,我已经看到了一个非常相似的工作条件。如:
"allOf": [
{
"if": {
"a0": true
},
"then": {
"required": [
"a1"
]
}
}
]
但这a1
需要j0
与a1
. 如何根据 underj1
的值要求对象 under j0
?
解决方案
尝试这个:
{
"if":{
"type":"object",
"properties":{
"i0":{
"type":"object",
"properties":{
"j0":{
"type":"object",
"required":["a0"]
}
},
"required":["j0"]
}
},
"required":["i0"]
},
"then":{
"type":"object",
"properties":{
"i1":{
"type":"object",
"properties":{
"j1":{
"type":"object",
"required":["a1"]
}
},
"required":["j1"]
}
},
"required":["i1"]
}
}
您必须使用if
/then
关键字中的整体结构,从它们具有的任何共同根开始。i0
在这种情况下,它们的路径在/属性处开始发散i1
,因此您必须从该点包含整个结构。
type
关键字确保您拥有一个对象,否则当使用其他类型(如 s 或 s)时,架构可能会通过string
验证boolean
。
required
关键字确保if
/then
子模式仅分别匹配实际包含i0.j0.a0
/i1.j1.a1
属性路径的对象。
此外,/`a1 属性的required
关键字a0
仅指定它们存在。如果需要,您可以向该子模式添加更多验证。
推荐阅读
- java - JPA UTC 时区查询谓词问题
- java - 尝试使用 base64 编码显示从服务器检索的图像但无法显示正确的图像
- javascript - Firebase onSnapshot 仅返回更改的项目
- macos - OSX 和 launchctl,rsync/ssh 找不到密钥
- python - Django 中的 TypeError:save() 得到了一个意外的关键字参数“force_insert”
- ada - Ada:在公共函数的前提条件中使用私有变量
- javascript - 提交句柄上状态更改的属性顺序
- python - 从 api 获取 json-format 到有用的 json-format (flask)
- javascript - React 组件返回映射项列表,然后消失
- android - 尝试在 Android 中写入外部/SD 存储