如何验证包含 MIXED 类型对象的 json 模式数组?

How can I validate a json schema array that contains a MIXED type of objects?

我已经搜索过,但还没有完全找到解决方案。

我想这样做一个模式:

...
"bag": {
   "type": "array",
   "items": {
      "anyOf": [
         {"$ref": "#/definitions/obj1"},
         {"$ref": "#/definitions/obj2"},
         {"$ref": "#/definitions/obj3"}
      ]
   },
   "required": ["items"],
   "minItems": 1
}
...

已定义对象:

...
"definitions": {
   "obj1": {
      "type": "object",
      "properties": {
         "obj1": {
            "type": "object",
            "properties": {
                "a": {
                   "type": "string"
                }
            },
            "required": ["a"]
         }
      }
   },
   "obj2": {
      "type": "object",
      "properties": {
         "obj1": {
            "type": "object",
            "properties": {
                "b": {
                   "type": "string"
                }
            },
            "required": ["b"]
         }
      }
   },
   "obj3": {
      "type": "object",
      "properties": {
         "obj1": {
            "type": "object",
            "properties": {
                "c": {
                   "type": "string"
                }
            },
            "required": ["c"]
         }
      }
   }
}
...

理想情况下,我想根据如下所示的架构进行验证:

...
"bag": [
   {
      "obj1": {"a": "test1"}
   },
   {
      "obj3": {"c": "test1"}
   }
]
...

在此上下文中,如果有人将 obj1obj3 传递给 bag。根据架构,obj1 需要 属性 a 并且 obj3 需要 属性 c.

我在实际执行时遇到了问题,因为验证似乎没有正确执行。

有什么建议吗?提前致谢。

根据您当前的架构和示例数据,我无法确切地说出您想要什么,但可以做出有根据的猜测...

我怀疑您想使用 oneOf 而不是 anyOf

anyOf 允许您匹配多个子模式,看起来您只想允许匹配其中一个子模式,obj1、2 或 3。

这会帮助您调试问题,但这并不是您总是通过验证的原因。

对于每个定义子模式,您需要添加"additionalProperties": false

这里是关键:JSON 架构是基于约束的,这意味着任何不受约束的东西都是允许的。

additionalProperties 将对象的允许属性限制为 properties(和 patternProperties)中定义的属性。

这是示例架构。您可以在此处看到它与您的实例一起使用:https://jsonschema.dev/s/MjBUp

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "definitions": {
    "obj1": {
      "type": "object",
      "properties": {
        "obj1": {
          "type": "object",
          "properties": {
            "a": {
              "type": "string"
            }
          },
          "required": ["a"]
        }
      },
      "additionalProperties": false
    },
    "obj2": {
      "type": "object",
      "properties": {
        "obj1": {
          "type": "object",
          "properties": {
            "b": {
              "type": "string"
            }
          },
          "required": ["b"]
        }
      },
      "additionalProperties": false
    }
 },
  "type": "array",
  "items": {
    "anyOf": [
      {"$ref": "#/definitions/obj1"},
      {"$ref": "#/definitions/obj2"}
    ]
  },
  "required": ["items"],
  "minItems": 1
}