我想验证 JSON 是否有一个对象数组。每个对象都有两个属性
tag
和 value
。
我想根据 value
字段验证 tag
。
例如:
if tag="collection date" value={SOME_REGEX}
else if tag="geographic location" value={SOME_ENUM}
....
else tag={ANY_STRING} value={ANY_STRING}
我用
contains
和 if then
尝试了几个不同的版本。但我认为以下是应该有效的。
使用
if then
和 allOf
关键字:这里不是匹配一个 if
条件,而是匹配所有条件。
我已将 tag
作为 required
属性包含在内,以避免与空架构匹配,但验证仍然与所有对象匹配。
(在线链接有错误)
数据
{
"alias": "lodBeiA",
"attributes": [
{
"tag": "collection date",
"value": "2021"
},
{
"tag": "geographic location",
"value": "UK"
},
{
"tag": "strain",
"value": "CBS 14171"
}
]
}
我尝试过的架构:
{
"$schema": "https://json-schema.org/draft/2019-09/schema",
"type": "object",
"properties": {
"alias": {
"type": "string"
},
"attributes": {
"type": "array",
"items": {
"type": "object",
"properties": {
"tag": {
"type": "string"
},
"value": {
"allOf": [
{
"if": {
"properties": {
"tag": {
"enum": [
"collection date"
]
}
},
"required": [
"tag"
]
},
"then": {
"type": "string",
"pattern": "(^[12][0-9]{3}(-(0[1-9]|1[0-2])(-(0[1-9]|[12][0-9]|3[01])(T[0-9]{2}:[0-9]{2}(:[0-9]{2})?Z?([+-][0-9]{1,2})?)?)?)?(/[0-9]{4}(-[0-9]{2}(-[0-9]{2}(T[0-9]{2}:[0-9]{2}(:[0-9]{2})?Z?([+-][0-9]{1,2})?)?)?)?)?$)"
}
},
{
"if": {
"properties": {
"tag": {
"enum": [
"geographic location"
]
}
},
"required": [
"tag"
]
},
"then": {
"enum": [
"UK",
"UGANDA"
]
}
},
{
"type": "string"
}
]
}
},
"required": [
"tag",
"value"
]
}
}
},
"additionalProperties": false,
"required": [
"alias",
"attributes"
]
}
if, then
应应用于要验证的属性的父级,而不是 properties
级别。
我还更新了您对
additionalProperties
的约束以使用 Draft-2019-09 关键字,unevaluatedProperties
{
"$schema": "https://json-schema.org/draft/2019-09/schema",
"type": "object",
"properties": {
"alias": {
"type": "string"
},
"attributes": {
"type": "array",
"items": {
"type": "object",
"properties": {
"tag": {
"type": "string"
},
"value": {
"type": "string"
}
},
"required": [
"tag",
"value"
],
"allOf": [
{
"if": {
"properties": {
"tag": {
"enum": [
"collection date"
]
}
},
"required": [
"tag"
]
},
"then": {
"properties": {
"value": {
"type": "string",
"pattern": "(^[12][0-9]{3}(-(0[1-9]|1[0-2])(-(0[1-9]|[12][0-9]|3[01])(T[0-9]{2}:[0-9]{2}(:[0-9]{2})?Z?([+-][0-9]{1,2})?)?)?)?(/[0-9]{4}(-[0-9]{2}(-[0-9]{2}(T[0-9]{2}:[0-9]{2}(:[0-9]{2})?Z?([+-][0-9]{1,2})?)?)?)?)?$)"
}
}
}
},
{
"if": {
"properties": {
"tag": {
"enum": [
"geographic location"
]
}
},
"required": [
"tag"
]
},
"then": {
"properties": {
"value": {
"enum": [
"UK",
"UGANDA"
]
}
}
}
}
]
}
}
},
"unevaluatedProperties": false,
"required": [
"alias",
"attributes"
]
}