Skip to main content
 首页 » 编程设计

python之使用 JSON Schema 将日期/时间字符串解析为日期时间

2025年02月15日21sxdcgaq8080

我可以使用 jsonschema 指定一个值是我的 JSON 对象中的有效日期,如下所示:

import jsonschema 
 
schema = {'type': 'object', 'properties': {'dt': {'type': 'string', 'format': 'date'}}} 
 
# fine 
jsonschema.validate({'dt': '2017-01-01'}, schema, format_checker=jsonschema.FormatChecker()) 
 
# jsonschema.exceptions.ValidationError: 'not a date' is not a 'date' 
jsonschema.validate({'dt': 'not a date'}, schema, format_checker=jsonschema.FormatChecker()) 

但是,这会使 dt 的值保持不变,仍然是一个字符串。我需要将日期/时间转换为 datetime.date/datetime.datetime 实例,在给定 JSON 模式(使用 jsonschema 或任何其他库?

理想情况下我想要这样的东西:

 import somelibrary 
 
 schema = {'type': 'object', 'properties': {'dt': {'type': 'string', 'format': 'date'}} 
 
 out = somelibrary.validate_and_parse({'dt': '2017-01-01'}, schema) 
 assert out == {'dt': datetime.date(2017, 1, 1)} 
 
 somelibrary.validate_and_parse({'dt': 'not a date'}, schema) # SomeError 

我有一个包含许多 JSON 文档的大型项目,这些文档可能非常大并且有很多嵌套级别,因此这并不像简单地自己查找键并在验证对象后处理它们那么容易。

请您参考如下方法:

您可以使用序列化库,例如 Marshmallow验证、序列化和反序列化您的数据。