d = {u'keyword': u'bad credit \xe7redit cards'}
with io.open('filename', 'w', encoding='utf8') as json_file:
data = json.dumps(d, ensure_ascii=False).decode('utf8')
try:
json_file.write(data)
except TypeError:
# Decode data to Unicode first
json_file.write(data.decode('utf8'))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 25: ordinal not in range(128)
with io.open('filename', 'w', encoding='utf8') as json_file:
json.dump(u"ברי צקלה", json_file, ensure_ascii=False)
请注意,有一个bug in the ^{} module,其中ensure_ascii=False标志可以生成unicode和str对象的混合。Python 2的解决方案是:
with io.open('filename', 'w', encoding='utf8') as json_file:
data = json.dumps(u"ברי צקלה", ensure_ascii=False)
# unicode(data) auto-decodes data to unicode if str
json_file.write(unicode(data))
Peters的python 2解决方案在边缘情况下失败:
它在第3行的.decode('utf8')部分崩溃。我通过避免该步骤以及ascii的特殊大小写,使程序更加简单,从而解决了这个问题:
使用
ensure_ascii=False
开关切换到json.dumps()
,然后手动将值编码为UTF-8:如果要写入文件,只需使用
json.dump()
并将其留给file对象进行编码:Python 2的注意事项
对于Python2,还有一些需要考虑的注意事项。如果要将其写入文件,可以使用^{} 而不是
open()
生成一个文件对象,在写入时为您编码Unicode值,然后使用json.dump()
而不是写入该文件:请注意,有一个bug in the ^{} module ,其中
ensure_ascii=False
标志可以生成unicode
和str
对象的混合。Python 2的解决方案是:在Python 2中,当使用编码为UTF-8的字节字符串(类型
str
)时,请确保还设置了encoding
关键字:写入文件
打印到标准输出
相关问题 更多 >
编程相关推荐