I tried to rewrite my class's str method, this is my code:
# encoding: utf8
import json
class Test(object):
def __str__(self):
d = {
'foo': u'中文'
}
return json.dumps(d, ensure_ascii=False)
test = Test()
print test.__str__()
print test
what make me confused is that print test.__str__()
works fine, but print test
cause exception:
Traceback (most recent call last):
File "test.py", line 17, in <module>
print(test)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 9-10: ordinal not in range(128)
python test.py 0.05s user 0.03s system 96% cpu 0.078 total
python version 2.7.12
__str__
must return a string value. If you return a unicode
object instead, it'll be automatically encoded as ASCII.
Encode explicitly instead:
class Test(object):
def __str__(self):
d = {
'foo': u'中文'
}
return json.dumps(d, ensure_ascii=False).encode('utf8')
Personally, I'd not use the __str__
method to provide a JSON encoding. Pick a different method name instead, like tojson()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.