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

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


当前回答

下面一行是伤害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字符,它不能被编码/解码。避免此错误的一个简单方法是使用encode()函数对这样的字符串进行编码,如下所示(如果a是非ascii字符的字符串):

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

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

将此标记为正确的临时修复(不确定)。

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

当我错误地试图像从文件中安装需求一样安装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()

在尝试了上述所有的解决方法之后,如果它仍然抛出相同的错误,您可以尝试将文件导出为CSV(如果已经导出了,可以第二次导出)。 特别是在使用scikit learn时,最好将数据集作为CSV文件导入。

我花了好几个小时在一起,而解决办法就这么简单。将文件以CSV格式导出到Anaconda或您的分类器工具安装的目录中并尝试。