我使用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() })

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


当前回答

而不是寻找解码a5 (Yen¥)或96 (en-dash -)的方法,告诉MySQL你的客户端编码为“latin1”,但你想在数据库中使用“utf8”。

详情见UTF-8字符的麻烦;我看到的不是我储存的

其他回答

简单的解决方案:

import pandas as pd
df = pd.read_csv('file_name.csv', engine='python')

而不是寻找解码a5 (Yen¥)或96 (en-dash -)的方法,告诉MySQL你的客户端编码为“latin1”,但你想在数据库中使用“utf8”。

详情见UTF-8字符的麻烦;我看到的不是我储存的

字符串中编码了一个非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了。

截至2018-05,这是直接用decode处理的,至少对于Python 3是这样。

我正在使用下面的片段来处理无效的开始字节和无效的延续字节类型错误。添加错误='忽略'为我修复了它。

with open(out_file, 'rb') as f:
    for line in f:
        print(line.decode(errors='ignore'))

在我的情况下,我必须将文件保存为UTF8 BOM,而不是UTF8 UTF8,然后这个错误就消失了。