Python'utf8'编解码器无法解码位置0中的字节0xcd:无效的连续字节

时间:2017-05-11 20:59:23

标签: python json dictionary

我正在尝试将下面的'字典'(x)转换为'JSON'。但我遇到以下数据不是JSON可序列化的。

STEP:1

>>> import json
>>> import datetime
>>> x={'status': 1, 'MetaInformation': {'create_time': datetime.datetime(2015, 6, 17, 7, 43),'last_saved_by': '\xcd\xf2\xbb\xa7\xcd\xf8\xc2\xe7','author': '\xcd\xf2\xbb\xa7\xcd\xf8\xc2\xe7','last_printed': datetime.datetime(2015, 6, 10, 6, 54), 'last_saved_time': datetime.datetime(2015, 6, 18, 0, 9)}}
>>> json_data=json.dumps(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/json/__init__.py", line 244, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python2.7/json/encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python2.7/json/encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: datetime.datetime(2015, 6, 10, 6, 54) is not JSON serializable

第2步:

我从字典中删除了几个字段来调试问题,

x={'status': 1, 'MetaInformation': {'create_time': datetime.datetime(2015, 6, 17, 7, 43),'last_printed': datetime.datetime(2015, 6, 10, 6, 54), 'last_saved_time': datetime.datetime(2015, 6, 18, 0, 9)}}

解决方案:

>>> from bson import json_util
>>> import json
>>> import datetime
>>> x={'status': 1, 'MetaInformation': {'create_time': datetime.datetime(2015, 6, 17, 7, 43),'last_printed': datetime.datetime(2015, 6, 10, 6, 54), 'last_saved_time': datetime.datetime(2015, 6, 18, 0, 9)}}
>>> y=json.dumps(x, default=json_util.default)
>>> print y
{"status": 1, "MetaInformation": {"create_time": {"$date": 1434526980000}, "last_saved_time": {"$date": 1434586140000}, "last_printed": {"$date": 1433919240000}}}

但是当我单独包含删除的数据(步骤2)以将字典转换为JSON数组时,我确实收到以下错误

>>> y=json.dumps(x, default=json_util.default)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/json/__init__.py", line 251, in dumps
    sort_keys=sort_keys, **kw).encode(obj)
  File "/usr/lib/python2.7/json/encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xcd in position 0: invalid continuation byte

我是python中的新手。将上面的字典(x)转换为JSON数组的任何帮助都会有帮助吗?

1 个答案:

答案 0 :(得分:1)

datetime.datetime没有返回字符串,因此json.dumps无法处理它。要更改它,请使用str(datetime.datetime(2015, 6, 17, 7, 43))