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 必须存在。
相关推荐
程序员三藏5 小时前
Python+requests实现接口自动化测试
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
一直走下去-明6 小时前
简单的http抓包解包完整代码
开发语言·python
雷帝木木6 小时前
数据湖与数据仓库:从理论到实践
人工智能·python·深度学习·机器学习
数字化转型分享点滴7 小时前
机加工车间上线 SH‑AIOT 物联网会遇到哪些常见实施难点
python·物联网
0566467 小时前
agent学习——流式响应与文本切分
网络·python·学习
OPEN-F7 小时前
Python进阶教程:正则表达式进阶与文本处理
开发语言·python·正则表达式
新网企兴7 小时前
2026年陕西做GEO推广,找新网企兴解决获客难题
python·搜索引擎
青 春 记 忆8 小时前
LeetCode 142. 环形链表 II|Python 解法详解
python·leetcode·链表
for_ever_love__8 小时前
python基础语法学习: 面向对象的三大特性
开发语言·python·学习
Spider赵毅8 小时前
Python爬虫踩坑实录:BeautifulSoup使用中的高频问题排查
爬虫·python·beautifulsoup