var schema = {
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "http://example.com/example.json",
"type": "object",
"required": [
"data"
],
"properties": {
"data": {
"$id": "#/properties/data",
"type": "object",
"required": [
"id",
"name",
"description",
"groups"
],
"properties": {
"id": {
"$id": "#/properties/data/properties/id",
"type": "integer"
},
"name": {
"$id": "#/properties/data/properties/name",
"type": "string"
},
"description": {
"$id": "#/properties/data/properties/description",
"type": "string"
},
"groups": {
"$id": "#/properties/data/properties/groups",
"type": "array",
"items": {
"$id": "#/properties/data/properties/groups/items",
"anyOf": [
{
"$id": "#/properties/data/properties/groups/items/anyOf/0",
"type": "object",
"required": [
"id",
"name",
"description"
],
"properties": {
"id": {
"$id": "#/properties/data/properties/groups/items/anyOf/0/properties/id",
"type": "integer"
},
"name": {
"$id": "#/properties/data/properties/groups/items/anyOf/0/properties/name",
"type": "string"
},
"description": {
"$id": "#/properties/data/properties/groups/items/anyOf/0/properties/description",
"type": "string"
}
}
}
]
}
}
}
}
}
};
我有JSON结果:
{
"data": {
"id": 1,
"name": "Contacts",
"description": "Pre-installed contacts management for your account.",
"groups": []
}
}
or
{
"data": {
"id": 4,
"name": "Update Container Sub Type 913",
"description": "I'll calculate the virtual SQL bus, that should circuit the FTP sensor!",
"groups": [
{
"id": 1,
"name": "tech",
"description": "tech description group"
}
]
}
}
当我验证JSON模式时,第二个有效,第一个 - 无效。 我该如何解决这两者都是有效的?
在JSON架构规范中描述的是2020-12版,可以验证数组中的最小项目数量。只需使用属性minItems
。 您可以写这样的东西:
{
"$id": "#/properties/data/properties/groups",
"type": "array",
"minItems": 1,
"items": {
...
}
}
已编辑:**这没有回答这个问题**Option 1:验证者和JSON-SCHEMA版本
anyOf
anyOf
anyOf
?
尝试: {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": [
"data"
],
"properties": {
"data": {
"$id": "#/properties/data",
"type": "object",
"required": [
"id",
"name",
"description",
"groups"
],
"properties": {
"id": {
"$id": "#/properties/data/properties/id",
"type": "integer"
},
"name": {
"$id": "#/properties/data/properties/name",
"type": "string"
},
"description": {
"$id": "#/properties/data/properties/description",
"type": "string"
},
"groups": {
"$id": "#/properties/data/properties/groups",
"type": "array",
"items": {
"$id": "#/properties/data/properties/groups/items/anyOf/0",
"type": "object",
"required": [
"id",
"name",
"description"
],
"properties": {
"id": {
"$id": "#/properties/data/properties/groups/items/anyOf/0/properties/id",
"type": "integer"
},
"name": {
"$id": "#/properties/data/properties/groups/items/anyOf/0/properties/name",
"type": "string"
},
"description": {
"$id": "#/properties/data/properties/groups/items/anyOf/0/properties/description",
"type": "string"
}
}
}
}
}
}
}
}
anyOf
约束,并验证一个空数组,因为默认情况下允许。
3:条件模式
如果您的验证器不接受空数数(有些确实),则可能有可能使用条件结构来处理某些内容。 。
一行:
如果数组大小为> 0,然后应用“ Anyof”子chema请让我们知道您如何解决此问题。