寻求支持JSON Schema Draft 7的Python JSON Schema验证器
支持JSON Schema Draft 7的Python验证器推荐
好问题!确实,官方的实现列表更新可能滞后了,目前已经有不少成熟的Python库支持JSON Schema Draft 7,下面给你推荐几个常用且靠谱的选项:
1. jsonschema
这是Python生态里最常用的JSON Schema验证库之一,从v3.0.0版本开始正式支持Draft 7,功能全面,文档完善,能覆盖Draft 7的所有核心特性。
- 安装:
pip install jsonschema>=3.0.0 - 简单验证示例:
import jsonschema from jsonschema import validate # 符合Draft 7规范的Schema draft7_schema = { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "username": {"type": "string", "minLength": 3}, "age": {"type": "integer", "minimum": 18} }, "required": ["username"] } # 验证有效数据 valid_data = {"username": "dev_user", "age": 22} try: validate(instance=valid_data, schema=draft7_schema) print("有效数据验证通过") except jsonschema.exceptions.ValidationError as err: print(f"验证失败: {err.message}") # 验证无效数据 invalid_data = {"username": "ab", "age": 17} try: validate(instance=invalid_data, schema=draft7_schema) print("无效数据验证通过") except jsonschema.exceptions.ValidationError as err: print(f"验证失败: {err.message}")
2. fastjsonschema
如果你的场景对验证性能有较高要求,这个库会是绝佳选择——它会把JSON Schema预编译成原生Python代码,运行速度比jsonschema快数倍,同时完全支持Draft 7。
- 安装:
pip install fastjsonschema - 性能优先的验证示例:
import fastjsonschema draft7_schema = { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "email": {"type": "string", "format": "email"}, "password": {"type": "string", "minLength": 8} }, "required": ["email", "password"] } # 编译Schema为验证函数(只需执行一次) validate_func = fastjsonschema.compile(draft7_schema) # 批量验证时性能优势明显 try: validate_func({"email": "user@example.com", "password": "secure_pass123"}) print("验证通过") except fastjsonschema.JsonSchemaException as err: print(f"验证失败: {err.message}")
3. Pydantic
虽然Pydantic主打数据类验证与序列化,但它完全兼容JSON Schema Draft 7,还能自动从Python数据类生成符合Draft 7规范的Schema,特别适合Web开发场景(比如配合FastAPI使用)。
- 安装:
pip install pydantic - 基于Schema的验证示例:
from pydantic import validate_json draft7_schema = { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "title": {"type": "string"}, "completed": {"type": "boolean"} }, "required": ["title"] } valid_json = '{"title": "Finish project", "completed": false}' invalid_json = '{"title": 123, "completed": "yes"}' # 直接验证JSON字符串 try: validate_json(valid_json, schema=draft7_schema) print("有效JSON验证通过") except ValueError as err: print(f"验证失败: {err}")
这些库都经过了广泛的社区测试,能稳定支持Draft 7的所有特性,你可以根据自己的需求(功能全面性、性能、是否需要数据类集成)来选择合适的工具。
内容的提问来源于stack exchange,提问作者xinyang gao
相关产品推荐
相关产品推荐

