Python jsonschema如何验证包含$ref引用的嵌套定义schema
问题解决:jsonschema带$ref的嵌套子schema验证方法
核心原因
你直接传入schemas['definitions']['user_record_with_ref']不生效的根本原因是:单独取出的子schema丢失了根schema的上下文,内部的$ref无法找到对应的定义节点,即使两个schema在同一个原始schema块内,只要你单独提取子schema传入,上下文就会断裂。
两种可行解决方案
方案1:给根schema指定$ref指向目标子schema(最简写法)
直接把包含所有定义的根schema作为验证的基础,同时用$ref指定要使用的子schema路径,完整的test_with_ref函数修改如下:
def test_with_ref(): try: validate( instance=user_record_object, # 保留完整根schema上下文,同时指向目标子schema schema={ **schemas, "$ref": "#/definitions/user_record_with_ref" } ) except jsonschema.exceptions.ValidationError as e: return f'JSON Error {e}', 400 return 'yay no problems'
方案2:预加载schema到Validator(适合多次验证的场景)
如果你的场景需要多次复用同一个根schema下的不同子schema,先创建Validator实例预加载完整schema,性能更高:
from jsonschema import Draft7Validator def test_with_ref(): # 预加载完整根schema,缓存所有定义和引用关系 validator = Draft7Validator(schemas) try: validator.validate( instance=user_record_object, schema=schemas['definitions']['user_record_with_ref'] ) except jsonschema.exceptions.ValidationError as e: return f'JSON Error {e}', 400 return 'yay no problems'
运行效果
两种方案运行后都会和无引用的验证逻辑一样,返回预期的校验失败结果:
('JSON Error -1 is less than the minimum of 1\n\nFailed validating \'minimum\' in schema[\'properties\'][\'uid\'][\'allOf\'][0]:\n {\'$id\': \'#uid\', \'type\': \'integer\', \'minimum\': 1}\n\nOn instance[\'uid\']:\n -1', 400)
内容的提问来源于stack exchange,提问作者Gabriel Clark
相关产品推荐
相关产品推荐

