我使用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()函数返回字典{}。

在发布这个问题之前,我已经提到了这个问题。


更新

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

但我不确定这是正确的做法。


当前回答

字符串中编码了一个非ascii字符。

如果需要在代码中使用其他编码,可能会出现无法使用utf-8解码的情况。例如:

>>> 'my weird character \x96'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x96 in position 19: invalid start byte

在这种情况下,编码是windows-1252,所以你必须做:

>>> 'my weird character \x96'.decode('windows-1252')
u'my weird character \u2013'

现在有了Unicode,就可以安全地编码为utf-8了。

其他回答

灵感来自@aaronpenne和@Soumyaansh

f = open("file.txt", "rb")
text = f.read().decode(errors='replace')

字符串中编码了一个非ascii字符。

如果需要在代码中使用其他编码,可能会出现无法使用utf-8解码的情况。例如:

>>> 'my weird character \x96'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x96 in position 19: invalid start byte

在这种情况下,编码是windows-1252,所以你必须做:

>>> 'my weird character \x96'.decode('windows-1252')
u'my weird character \u2013'

现在有了Unicode,就可以安全地编码为utf-8了。

在代码顶部设置默认编码器

import sys
reload(sys)
sys.setdefaultencoding("ISO-8859-1")

我知道这并不直接适合这个问题,但当我谷歌错误消息时,我反复被引导到这个问题。

当我错误地试图像从文件中安装需求一样安装Python包时,即使用-r时,我确实得到了错误:

# wrong: leads to the error above
pip install -r my_package.whl

# correct: without -r
pip install my_package.whl

我希望这能帮助那些和我犯同样小错误的人。

试试下面的代码片段:

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