我有JSON数据,它是一个数据数组,例如
[
{
"type": "background_color",
"data": {
"backgroundColor": "F9192D"
}
},
{
"type": "banner_images",
"data": {
"images": [
{
"url": "https://example.com/abc.jpg",
"id": 3085
},
{
"url": "https://example.com/zyx.jpg",
"id": 3086
}
]
}
},
{
"type": "description_box",
"data": {
"text": "Hello 56787"
}
}
]
数据是具有两个键type
和data
的对象数组。 data
的类型和键将由其具有的数据的type
定义。
[类似于background_color
类型,data
应该具有backgroundColor
属性,而对于banner_images
,data
应该具有images
,它是其他属性的数组。
到现在为止,我所做的是
{
"definitions": {},
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "array",
"title": "category schema",
"description": "Used to validate data of category",
"examples": [],
"required": [],
"items": {
"type": "object",
"required": [
"type",
"data"
],
"properties": {
"type": {
"type": "string",
"enum": ["background_color", "banner_images", "description_box"]
},
"data": {
"type": "object" // How to define data property here for each use case
}
}
}
}
我不知道如何为每个用例定义data
属性?
您可以使用if/then/else
块来定义条件约束。
if
和then
的值是模式。如果if
模式有效,则将应用then
模式,否则allOf
子模式(在此示例中为allOf[0]
)将通过验证。
有几种不同的方法可以做到这一点,但是当您没有任何其他或特殊要求时,这是干净的。如果愿意,请回来=]
在此示例中,我添加了banner_images
...
您可以通过here对其进行测试。
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "array",
"title": "category schema",
"description": "Used to validate data of category",
"items": {
"type": "object",
"required": [
"type",
"data"
],
"properties": {
"type": {
"type": "string",
"enum": [
"background_color",
"banner_images",
"description_box"
]
},
"data": {
"type": "object"
}
},
"allOf": [
{
"if": {
"properties": {
"type": {
"const": "banner_images"
}
}
},
"then": {
"properties": {
"data": {
"required": [
"images"
],
"properties": {
"images": {
"type": "array"
}
}
}
}
}
}
]
}
}
作为参考,这是JSON Schema draft-7规范文档的一部分,详细说明了行为:https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.6