swi*_*ers 2 json jsonschema json-schema-validator
我有一个 JSON:
{
"i0": {
"j0": {
"a0": true
}
},
"i1": {
"j1": {
"a1": "stuff"
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想要一个验证:如果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"
]
}
}
}
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
该条件似乎实际上并未运行。required或者,如果我尝试将其置于与我正在检查的值相同的水平上,我已经看到了非常相似的条件。如:
"allOf": [
{
"if": {
"a0": true
},
"then": {
"required": [
"a1"
]
}
}
]
Run Code Online (Sandbox Code Playgroud)
但这需要与 一起a1在下面。如何根据 下的值要求下一个对象?j0a1j1j0
尝试这个:
{
"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"]
}
}
Run Code Online (Sandbox Code Playgroud)
您必须使用if/then关键字中的整体结构,从它们具有的任何共同根开始。i0在这种情况下,它们的路径在/属性处开始分叉i1,因此您必须包含从该点开始的整个结构。
关键字确保您拥有一个对象,否则当使用其他类型(如s 或s)type时,架构可能会通过验证。stringboolean
关键字required确保if/then子模式仅分别匹配实际包含i0.j0.a0/i1.j1.a1属性路径的对象。
此外, /`a1 属性required的关键字a0仅指定它们存在。如果需要,您可以向该子模式添加更多验证。