我在使用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(__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 {}
。
在发布这个问题之前,我参考了this的问题os SO。
下面一行是伤害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() })
将此标记为正确的临时修复(不确定是否如此)。