如何在 json 模式中使用逻辑 if else 来验证数组项?
How to use logic if else in json schema to validate array item?
我有json这样的
{ "user" : ["foo", "bar"] }
我想在这里使用 if else
如果数组 user 中有 "foo",则需要字段 admin
我试过这样
{
"$schema": "http://json-schema.org/draft-07/schema",
"title": "JSON Schema for role",
"type": "object",
"properties": {
"user": {
"type": ["array"],
"items" : {
"type" : "string",
"enum" : [
"foo",
"bar"
]
}
},
"admin" : {"type" : "string"},
"if": {
"properties": {
"user": { "const": "foo" }
},
"required": ["user"]
},
"then": { "required": ["admin"] }
},"additionalProperties": false}
但不起作用
const
适用于单个值,但您想检查数组的内容。
你想要contains
。 contains
将它的值(这是一个子模式)应用于数组中的每个项目,以检查至少一个项目是预期的。
您还需要让 if
和 then
关键字成为架构对象的一部分。您将它们作为 properties
对象的一部分。
{
"$schema": "http://json-schema.org/draft-07/schema",
"title": "JSON Schema for role",
"type": "object",
"properties": {
"user": {
"type": [
"array"
],
"items": {
"type": "string",
"enum": [
"foo",
"bar"
]
}
},
"admin": {
"type": "string"
}
},
"required": [
"user"
],
"if": {
"properties": {
"user": {
"contains": {
"type": "string",
"const": "foo"
}
}
}
},
"then": {
"required": [
"admin"
]
},
"additionalProperties": false
}
我有json这样的
{ "user" : ["foo", "bar"] }
我想在这里使用 if else
如果数组 user 中有 "foo",则需要字段 admin
我试过这样
{
"$schema": "http://json-schema.org/draft-07/schema",
"title": "JSON Schema for role",
"type": "object",
"properties": {
"user": {
"type": ["array"],
"items" : {
"type" : "string",
"enum" : [
"foo",
"bar"
]
}
},
"admin" : {"type" : "string"},
"if": {
"properties": {
"user": { "const": "foo" }
},
"required": ["user"]
},
"then": { "required": ["admin"] }
},"additionalProperties": false}
但不起作用
const
适用于单个值,但您想检查数组的内容。
你想要contains
。 contains
将它的值(这是一个子模式)应用于数组中的每个项目,以检查至少一个项目是预期的。
您还需要让 if
和 then
关键字成为架构对象的一部分。您将它们作为 properties
对象的一部分。
{
"$schema": "http://json-schema.org/draft-07/schema",
"title": "JSON Schema for role",
"type": "object",
"properties": {
"user": {
"type": [
"array"
],
"items": {
"type": "string",
"enum": [
"foo",
"bar"
]
}
},
"admin": {
"type": "string"
}
},
"required": [
"user"
],
"if": {
"properties": {
"user": {
"contains": {
"type": "string",
"const": "foo"
}
}
}
},
"then": {
"required": [
"admin"
]
},
"additionalProperties": false
}