小编典典

Python-UnicodeDecodeError:“ utf8”编解码器无法解码位置0的字节0xa5:无效的起始字节

python

我正在使用Python-2.6 CGI脚本,但是在执行服务器日志时发现此错误json.dumps()

Traceback (most recent call last):
  File "/etc/mongodb/server/cgi-bin/getstats.py", line 135, in <module>
    print json.dumps(​​__get​data())
  File "/usr/lib/python2.7/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python2.7/json/encoder.py", line 201, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python2.7/json/encoder.py", line 264, in iterencode
    return _iterencode(o, 0)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

这里

​__get​data()函数返回dictionary {}

张贴这个问题之前我已经提到这个问题,操作系统,所以的。

更新
下一行损害了JSON编码器,

now = datetime.datetime.now()
now = datetime.datetime.strftime(now, '%Y-%m-%dT%H:%M:%S.%fZ')
print json.dumps({'current_time': now}) // this is the culprit

我有一个临时解决方案

print json.dumps( {'old_time': now.encode('ISO-8859-1').strip() })

但是我不确定这样做是否正确。


阅读 1120

收藏
2020-02-22

共2个答案

小编典典

该错误是因为字典中存在一些非ASCII字符,并且无法对其进行编码/解码。避免此错误的一种简单方法是使用encode()如下函数对此类字符串进行编码(如果a字符串为非ascii字符):

a.encode('utf-8').strip()
2020-02-22
小编典典

试试下面的代码片段:

with open(path, 'rb') as f:
  text = f.read()
2020-02-22