You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中用JSON Schema有效验证日期格式?

解决JSON Schema中date格式验证不生效的问题

你的问题核心在于:jsonschema库默认不强制执行format关键字的验证逻辑,format默认只是作为元数据注解存在,不会主动校验格式是否符合要求。要实现有效的日期格式验证,只需显式开启格式检查即可,无需手写正则表达式。

解决方案:开启格式检查

在调用jsonschema.validate()时,添加check_formats=True参数,就能让format: "date"的规则生效:

修改后的完整代码:

import jsonschema

# Define JSON object
json_object = {
    "date": "21ducn23-dsfsd-ds",
    "age": 30
}

# Define JSON schema with date format
json_schema = {
    "type": "object",
    "properties": {
        "date": {"type": "string", "format": "date"},
        "age": {"type": "integer"},
    },
    "required": ["date", "age"],
} 

# Validate with format checking enabled
jsonschema.validate(instance=json_object, schema=json_schema, check_formats=True)

效果说明

  • 当date字段符合ISO 8601标准日期格式(如"2024-05-20")时,验证会通过;
  • 像你示例中的"21ducn23-dsfsd-ds"这类不符合格式的字符串,会直接抛出jsonschema.exceptions.ValidationError,提示日期格式不符合要求。

另一种等价写法:使用FormatChecker

也可以通过FormatChecker类开启格式验证,效果完全一致:

from jsonschema import FormatChecker

jsonschema.validate(instance=json_object, schema=json_schema, format_checker=FormatChecker())

版本适配说明

你使用的jsonschema==4.21.1版本中,check_formats参数默认值为"ignore",因此必须显式设置为True(或"strict")才能启用格式校验。这个参数是4.x版本新增的简化写法,替代了旧版本中必须手动传入FormatChecker的方式。

内容的提问来源于stack exchange,提问作者JabbaThePadd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 12:33:18