如何在JSON Schema中实现data属性类型的互斥或验证?
JSON Schema实现
data属性的互斥或(XOR)验证 问题背景
我有一个JSON文件,内容为对象数组,每个对象包含唯一的data属性,该属性值可为字符串或数组;若为数组,其元素可为字符串或对象。
原使用的JSON Schema如下:
{ "$id": "https://mycomp.com/myjson.schema.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "data", "type": "array", "items": { "type": "object", "properties": { "data": { "anyOf": [ { "$ref": "#/$defs/file" }, { "$ref": "#/$defs/inline" } ] } } }, "$defs": { "file": { "type": "string" }, "inline": { "type": "array", "items": { "anyOf": [ {"type": "string"}, {"type": "object"} ] } } } }
验证以下JSON时,结果显示为有效:
[ { "data": [ "This is a string", {"prop1": 1, "prop2": "2"} ] } ]
即使将Schema中的anyOf替换为oneOf,验证结果依然有效。需要实现对data属性类型的严格互斥或(XOR)验证。
解决方法
你当前的测试JSON本来就只符合oneOf中的一个分支(inline数组类型),所以验证通过是正常的——oneOf本身就是互斥或逻辑,要求实例恰好匹配其中一个子Schema。
如果要确保data属性严格只能是字符串或数组(完全互斥,不存在同时符合两种类型的可能),可以在每个定义的子Schema中明确排除另一种类型,修改后的Schema如下:
{ "$id": "https://mycomp.com/myjson.schema.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "data", "type": "array", "items": { "type": "object", "properties": { "data": { "oneOf": [ { "$ref": "#/$defs/file" }, { "$ref": "#/$defs/inline" } ] } }, "required": ["data"] }, "$defs": { "file": { "type": "string", "not": { "type": "array" } }, "inline": { "type": "array", "not": { "type": "string" }, "items": { "anyOf": [ {"type": "string"}, {"type": "object"} ] } } } }
关键逻辑说明
oneOf关键字确保实例只能匹配其中一个子Schema,实现基础的互斥;- 每个子Schema中加入
not关键字,明确排除另一种类型,彻底杜绝同时符合两种类型的可能性(虽然JSON中字符串和数组本身是互斥类型,但添加该约束可以让Schema的逻辑更清晰,也能避免后续修改时出现意外兼容); - 额外添加
required: ["data"],确保每个对象必须包含data属性,匹配你“每个对象包含唯一的data属性”的需求。
内容的提问来源于stack exchange,提问作者Mr T.
相关产品推荐
相关产品推荐

