UnicodeDecodeError: 'utf8' 编解码器无法解码位置 0 中的字节 0xa5:起始字节无效 [英] UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte
问题描述
我正在使用 Python-2.6 CGI
脚本,但在执行 json.dumps()
时在服务器日志中发现此错误,
I am using Python-2.6 CGI
scripts but found this error in server log while doing json.dumps()
,
Traceback (most recent call last):
File "/etc/mongodb/server/cgi-bin/getstats.py", line 135, in <module>
print json.dumps(__getdata())
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 {}
.
在发布这个问题之前,我已经提到了this 问题 os SO.
Before posting this question I have referred this of question os SO.
以下内容正在损害 JSON 编码器,
Following line is hurting JSON encoder,
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() })
但我不确定这样做是否正确.
But I am not sure is it correct way to do it.
推荐答案
错误是因为字典中有一些非ascii字符,无法编码/解码.避免此错误的一种简单方法是使用 encode()
函数对此类字符串进行编码,如下所示(如果 a
是具有非 ascii 字符的字符串):
The error is because there is some non-ascii character in the dictionary and it can't be encoded/decoded. One simple way to avoid this error is to encode such strings with encode()
function as follows (if a
is the string with non-ascii character):
a.encode('utf-8').strip()
这篇关于UnicodeDecodeError: 'utf8' 编解码器无法解码位置 0 中的字节 0xa5:起始字节无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!