I am using Python-2.6 CGI
scripts but found this error in server log while doing json.dumps()
,
JavaScript
x
11
11
1
Traceback (most recent call last):
2
File "/etc/mongodb/server/cgi-bin/getstats.py", line 135, in <module>
3
print json.dumps(••__get•data())
4
File "/usr/lib/python2.7/json/__init__.py", line 231, in dumps
5
return _default_encoder.encode(obj)
6
File "/usr/lib/python2.7/json/encoder.py", line 201, in encode
7
chunks = self.iterencode(o, _one_shot=True)
8
File "/usr/lib/python2.7/json/encoder.py", line 264, in iterencode
9
return _iterencode(o, 0)
10
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte
11
Here ,
__getdata()
function returns dictionary {}
.
Before posting this question I have referred this of question os SO.
UPDATES
Following line is hurting JSON encoder,
JavaScript
1
4
1
now = datetime.datetime.now()
2
now = datetime.datetime.strftime(now, '%Y-%m-%dT%H:%M:%S.%fZ')
3
print json.dumps({'current_time': now}) # this is the culprit
4
I got a temporary fix for it
JavaScript
1
2
1
print json.dumps( {'old_time': now.encode('ISO-8859-1').strip() })
2
But I am not sure is it correct way to do it.
Advertisement
Answer
The error is because there is some non-ascii character in the dictionary and it can’t be encoded/decoded. One simple way to avoid this error is to encode such strings with encode()
function as follows (if a
is the string with non-ascii character):
JavaScript
1
2
1
a.encode('utf-8').strip()
2