JSON 架构:数组元素之间的依赖关系
JSON Schema: Dependency across array elements
如果存在其他数组元素,要求具有特定字段的数组元素的正确方法是什么?
例如。如果 butter
在这里,则强制 bread
:
+-------+-------+--------+
| valid | bread | butter |
+-------+-------+--------+
| + | - | - |
| + | + | - |
| + | + | + |
| - | - | + |
+-------+-------+--------+
产品示例:
{
"products": [
{
"name": "butter"
},
{
"name": "bread"
}
]
}
基于 and Combining schemas,可以检查没有butter
,否则array有bread
:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Complex Array",
"anyOf": [
{ "not": { "$ref": "#/definitions/contains-name-butter" } },
{ "$ref": "#/definitions/contains-name-bread" }
],
"definitions": {
"contains-name-butter": {
"type": "object",
"properties": {
"products": {
"type": "array",
"contains": {
"type": "object",
"properties": {
"name": {
"type": "string",
"pattern": "^butter$"
}
}
}
}
}
},
"contains-name-bread": {
"type": "object",
"properties": {
"products": {
"type": "array",
"contains": {
"type": "object",
"properties": {
"name": {
"type": "string",
"pattern": "^bread$"
}
}
}
}
}
}
}
}
现在,如果 bread
被删除 - 模式验证将中断。
有什么办法可以让它更简单吗?特别是如果将来计划添加更多依赖项。
从逻辑上讲,您似乎想要的是:如果数组包含 属性 "name" 且值为 "butter" 的项目,则需要 [=21] 的项目=] "name" 和值 "bread":
"type" : "array",
"if" : {
"contains" : {
"type: "object",
"properties" : {
"name" : {
"const" : "butter"
}
}
}
},
"then" : {
"contains" : {
"required": [ "name" ],
"properties" : {
"name" : {
"const" : "bread"
}
}
}
}
}
(我也把"pattern": "^bread$"
简化为"const":"bread"
。)
如果存在其他数组元素,要求具有特定字段的数组元素的正确方法是什么?
例如。如果 butter
在这里,则强制 bread
:
+-------+-------+--------+
| valid | bread | butter |
+-------+-------+--------+
| + | - | - |
| + | + | - |
| + | + | + |
| - | - | + |
+-------+-------+--------+
产品示例:
{
"products": [
{
"name": "butter"
},
{
"name": "bread"
}
]
}
基于butter
,否则array有bread
:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Complex Array",
"anyOf": [
{ "not": { "$ref": "#/definitions/contains-name-butter" } },
{ "$ref": "#/definitions/contains-name-bread" }
],
"definitions": {
"contains-name-butter": {
"type": "object",
"properties": {
"products": {
"type": "array",
"contains": {
"type": "object",
"properties": {
"name": {
"type": "string",
"pattern": "^butter$"
}
}
}
}
}
},
"contains-name-bread": {
"type": "object",
"properties": {
"products": {
"type": "array",
"contains": {
"type": "object",
"properties": {
"name": {
"type": "string",
"pattern": "^bread$"
}
}
}
}
}
}
}
}
现在,如果 bread
被删除 - 模式验证将中断。
有什么办法可以让它更简单吗?特别是如果将来计划添加更多依赖项。
从逻辑上讲,您似乎想要的是:如果数组包含 属性 "name" 且值为 "butter" 的项目,则需要 [=21] 的项目=] "name" 和值 "bread":
"type" : "array",
"if" : {
"contains" : {
"type: "object",
"properties" : {
"name" : {
"const" : "butter"
}
}
}
},
"then" : {
"contains" : {
"required": [ "name" ],
"properties" : {
"name" : {
"const" : "bread"
}
}
}
}
}
(我也把"pattern": "^bread$"
简化为"const":"bread"
。)