gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:10:11 25 4
gpt4 key购买 nike

我可以使用 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验证、序列化和反序列化您的数据。

关于python - 使用 JSON Schema 将日期/时间字符串解析为日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43190502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com