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

2024-04-23 13:06:13 发布

您现在位置: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 {}

在发布这个问题之前,我已经引用了问题os SO的this


更新

下面这一行伤害了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() })

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


Tags: inpyjsonencodergetdatetimelibusr
3条回答

请尝试以下代码段:

with open(path, 'rb') as f:
  text = f.read()

我只是通过在read_csv()命令中定义不同的编解码器包来切换:

encoding = 'unicode_escape'

错误是因为字典中有一些非ascii字符,无法对其进行编码/解码。避免此错误的一个简单方法是使用encode()函数对此类字符串进行编码,如下所示(如果a是具有非ascii字符的字符串):

a.encode('utf-8').strip()

相关问题 更多 >