jsonshema小点

一、什么是 dependentRequired 单向限制?

它的核心逻辑是:

**如果 A 字段存在,那么 B 字段必须同时存在;但反过来,B 字段存在时,A 字段可以不存在。**也就是我们常说的「单向依赖」。


二、结合示例拆解

复制代码
{
  "type": "object",
  "properties": {
    "creditCard": { "type": "string" },
    "billingAddress": { "type": "string" }
  },
  "dependentRequired": {
    "creditCard": ["billingAddress"]
  }
}

规则解读

  • 这行 "creditCard": ["billingAddress"] 表示: 只要 creditCard(信用卡号)字段出现了,billingAddress(账单地址)字段必须同时出现
  • 反过来,如果只有 billingAddress,没有 creditCard,是完全合法的。

合法 / 非法场景对比

表格

JSON 数据 校验结果 原因
{"creditCard": "123456", "billingAddress": "北京"} ✅ 通过 依赖规则触发,两个字段都存在
{"billingAddress": "北京"} ✅ 通过 只有被依赖字段,没有触发依赖规则
{} ✅ 通过 两个字段都不存在,不触发规则
{"creditCard": "123456"} ❌ 失败 触发了依赖规则,但缺少 billingAddress

三、报错解析

报错信息:

复制代码
json-schema.exceptions.ValidationError: 'loginUser' is a required property
Failed validating 'required' in schema['properties']['data']['items']:
{'type': 'object', 'required': ['id', 'loginUser'], ...}

这个报错是因为用了 required,而不是 dependentRequired

  • 写了 "required": ["id", "loginUser"],意思是:不管什么情况,idloginUser 两个字段都必须存在,这是强制的,和依赖无关。
  • 如果你想改成「只有当某个字段存在时,loginUser 才必须存在」,就要用 dependentRequired,而不是直接写 required

四、完整可运行示例(带单向依赖)

复制代码
from jsonschema import validate

def test_dependent_required():
    # 1. 合法场景:creditCard 和 billingAddress 同时存在
    valid1 = {
        "creditCard": "4111-1111-1111-1111",
        "billingAddress": "北京市朝阳区"
    }

    # 2. 合法场景:只有 billingAddress,没有 creditCard
    valid2 = {
        "billingAddress": "上海市浦东新区"
    }

    # 3. 合法场景:两个字段都不存在
    valid3 = {}

    # 4. 非法场景:只有 creditCard,没有 billingAddress
    invalid = {
        "creditCard": "4111-1111-1111"
    }

    # 带单向依赖的 Schema
    schema = {
        "type": "object",
        "properties": {
            "creditCard": {"type": "string"},
            "billingAddress": {"type": "string"}
        },
        "dependentRequired": {
            "creditCard": ["billingAddress"]
        }
    }

    # 校验合法数据
    validate(instance=valid1, schema=schema)
    validate(instance=valid2, schema=schema)
    validate(instance=valid3, schema=schema)
    print("✅ 所有合法场景校验通过")

    # 校验非法数据(会报错)
    # validate(instance=invalid, schema=schema)

五、和 required 的核心区别

关键字 作用 适用场景
required 强制字段必须存在,和其他字段无关 无论什么情况,字段都不能少
dependentRequired 字段存在时,其他字段必须同时存在 字段之间有依赖关系,比如 "有信用卡号就必须有账单地址"

💡 小技巧:

  • 一个字段可以依赖多个字段,比如 "age": ["height", "gender"],表示有 age 时,heightgender 都必须存在。
  • 多个字段也可以依赖同一个字段,比如 "a": ["c"], "b": ["c"],表示有 ab 时,c 必须存在。
相关推荐
星云穿梭13 小时前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵13 小时前
用 Pygame 实现 15 puzzle
python·数学·游戏
黄忠19 小时前
大模型之LangGraph技术体系
python·llm
hboot1 天前
AI工程师第二课 - 数据处理
人工智能·python·数据分析
用户8356290780512 天前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
用户8356290780512 天前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
黄忠2 天前
01-系统架构设计-LangGraph状态机与多源异构RAG
python
zzzzzz3102 天前
假如我是掘金管理员,我先给评论区装个'代码审查'系统
python·程序员·机器人
砍材农夫2 天前
python环境|conda安装和使用(2)
后端·python
程序员龙叔2 天前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试