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))
使用
ensure_ascii=False
开关切换到json.dumps()
,然后手动将值编码为UTF-8:如果要写入文件,只需使用
json.dump()
,并将其留给file对象进行编码:Python 2的注意事项
对于Python 2,还有一些需要考虑的注意事项。如果要将此写入文件,可以使用^{} 而不是
open()
生成一个在写入时为您编码Unicode值的文件对象,然后使用json.dump()
而不是写入该文件:请注意,有一个bug in the ^{} module ,其中
ensure_ascii=False
标志可以生成unicode
和str
对象的混合。Python 2的解决方法是:在Python 2中,使用编码为UTF-8的字节字符串(键入
str
)时,请确保还设置了encoding
关键字:写入文件
打印到stdin
更新:这是一个错误的答案,但是理解为什么是错误的仍然是有用的。见评论。
那
unicode-escape
怎么样?相关问题 更多 >
编程相关推荐