我有以下json文件:
{'a': {'$gt': datetime.datetime(2020, 1, 1, 0, 0)}} 我将其转换为字符串并替换为‘--> "":
>>> x
'{"a": {"$gt": datetime.datetime(2020, 1, 1, 0, 0)}}'加载json时出错:
>>> json.loads(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python36\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "C:\Python36\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python36\lib\json\decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 15 (char 14)发布于 2020-02-13 03:25:24
该问题已得到解决。由以下事实引起的问题:“datetime.datetime不是JSON序列化”
from json import dumps
from datetime import date, datetime
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime, date)):
return obj.isoformat()
raise TypeError ("Type %s not serializable" % type(obj))导入此函数后:
>>> x
{'a': {'$gt': datetime.datetime(2020, 1, 1, 0, 0)}}
>>> x=dumps(x,default=json_serial)
>>> x
'{"a": {"$gt": "2020-01-01T00:00:00"}}'
>>>
>>>
>>> json.loads(x)
{'a': {'$gt': '2020-01-01T00:00:00'}}
>>>https://stackoverflow.com/questions/60194623
复制相似问题