UnicodeDecodeError:'utf8'編解碼器無法解碼位置0中的字節(jié)0xa5:無效的起始字節(jié)我正在使用Python-2.6 CGI腳本,但在服務器日志中發(fā)現(xiàn)此錯誤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在這里,__getdata()功能返回dictionary {}。更新以下行是傷害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() })但我不確定這是否正確。
3 回答

達令說
TA貢獻1821條經(jīng)驗 獲得超6個贊
該錯誤是因為字典中存在一些非ascii字符,并且無法對其進行編碼/解碼。避免此錯誤的一種簡單方法是使用以下encode()
函數(shù)對此類字符串進行編碼(如果a
是具有非ascii字符的字符串):
a.encode('utf-8').strip()
添加回答
舉報
0/150
提交
取消