如何用单个JSON Schema实现download_data与upload_data的OR校验?
解决方案
单个JSON Schema实现OR校验
要实现download_data和upload_data至少存在一个的校验,可利用JSON Schema的anyOf关键字结合required约束,同时定义两个任务各自的结构规则。以下是完整的Schema:
{ "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "required": ["tasks"], "properties": { "tasks": { "type": "object", "properties": { "download_data": { "type": "object", "required": ["targetdir", "Rest"], "properties": { "targetdir": { "type": "string" }, "Rest": { "type": "object", "required": ["type", "server", "api_version", "source", "user", "password"], "properties": { "type": { "type": "string" }, "server": { "type": "string" }, "api_version": { "type": "string" }, "source": { "type": "string" }, "user": { "type": "string" }, "password": { "type": "string" } } } } }, "upload_data": { "type": "object", "required": ["zip", "database_server"], "properties": { "zip": { "type": "string" }, "database_server": { "type": "object", "required": ["host", "port", "database", "user", "password"], "properties": { "host": { "type": "string" }, "port": { "type": "string" }, "database": { "type": "string" }, "user": { "type": "string" }, "password": { "type": "string" } } } } } }, "additionalProperties": false, "anyOf": [ { "required": ["download_data"] }, { "required": ["upload_data"] } ] } }, "additionalProperties": false }
关键说明:
anyOf关键字确保tasks对象至少满足其中一个子约束:要么包含download_data,要么包含upload_data,两者同时存在也符合规则。additionalProperties: false限制tasks下只能有指定的两个任务键,你第三个示例中的upload_report应为笔误,需改为upload_data才能通过校验。- 每个任务的
required字段定义了该任务必须包含的属性,保证配置的完整性。
Python校验代码示例
使用jsonschema库进行校验的示例代码:
import json from jsonschema import validate, ValidationError # 加载上述Schema with open("task_schema.json", "r") as f: task_schema = json.load(f) # 加载待校验的JSON配置 with open("task_config.json", "r") as f: task_config = json.load(f) try: validate(instance=task_config, schema=task_schema) print("配置校验通过") except ValidationError as e: print(f"配置校验失败: {e.message}")
JSON Schema进阶学习资源
- 官方核心规范文档:重点研读JSON Schema Draft 2020-12的规范内容,它涵盖了所有高级关键字的用法和设计思路,是最权威的参考资料。
- 实战书籍:《JSON Schema in Action》,这本书通过大量实际案例讲解Schema的设计技巧,包括复杂约束、复用结构等进阶内容。
- 社区讨论:关注Stack Overflow的
json-schema标签,里面有很多开发者遇到的实际问题和解决方案,能帮助你快速掌握复杂场景的处理方法。 - Schema复用技巧:学习使用
$ref和$defs关键字实现Schema片段的复用,这在大型项目中能大幅提升Schema的可维护性。
内容的提问来源于stack exchange,提问作者user8276908
相关产品推荐
相关产品推荐

