gpt4 book ai didi

python - 如何克服 "datetime.datetime not JSON serializable"?

转载 作者:行者123 更新时间:2023-12-03 15:59:45 24 4
gpt4 key购买 nike

我有一个基本的字典如下:

sample = {}
sample['title'] = "String"
sample['somedate'] = somedatetimehere

当我尝试执行 jsonify(sample) 时,我得到:

TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable

我该怎么做才能使我的词典样本能够克服上述错误?

注意:虽然可能不相关,但字典是从 mongodb 中检索记录生成的,当我打印出 str(sample[ 'somedate']),输出为 2012-08-08 21:46:24.862000

最佳答案

我的快速而肮脏的 JSON 转储会吃掉日期和所有内容:

json.dumps(my_dictionary, indent=4, sort_keys=True, default=str)

default is a function applied to objects that aren't serializable.
In this case it's str, so it just converts everything it doesn't know to strings. Which is great for serialization but not so great when deserializing (hence the "quick & dirty") as anything might have been string-ified without warning, e.g. a function or numpy array.

关于python - 如何克服 "datetime.datetime not JSON serializable"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46608814/

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