使用
ensure_ascii=False切换至
json.dumps(),然后手动将值编码为UTF-8:
>>> json_string = json.dumps("ברי צקלה", ensure_ascii=False).enpre('utf8')>>> json_stringb'"xd7x91xd7xa8xd7x99 xd7xa6xd7xa7xd7x9cxd7x94"'>>> print(json_string.depre())"ברי צקלה"如果要写入文件,只需使用
json.dump()并将其留给文件对象进行编码:
with open('filename', 'w', encoding='utf8') as json_file: json.dump("ברי צקלה", json_file, ensure_ascii=False)Python 2警告
对于Python
2,还有更多注意事项需要考虑。如果要将其写入文件,则可以使用
io.open()代替
open()来生成一个文件对象,该对象在编写时为您编码Unipre值,然后使用
json.dump()代替来写入该文件:
with io.open('filename', 'w', encoding='utf8') as json_file: json.dump(u"ברי צקלה", json_file, ensure_ascii=False)做笔记,有一对在错误
json模块,其中
ensure_ascii=False标志可以产生一个
混合 的
unipre和
str对象。那么,Python 2的解决方法是:
with io.open('filename', 'w', encoding='utf8') as json_file: data = json.dumps(u"ברי צקלה", ensure_ascii=False) # unipre(data) auto-depres data to unipre if str json_file.write(unipre(data))在Python 2中,当使用
str编码为UTF-8的字节字符串(类型)时,请确保还设置
encoding关键字:
>>> d={ 1: "ברי צקלה", 2: u"ברי צקלה" }>>> d{1: 'xd7x91xd7xa8xd7x99 xd7xa6xd7xa7xd7x9cxd7x94', 2: u'u05d1u05e8u05d9 u05e6u05e7u05dcu05d4'}>>> s=json.dumps(d, ensure_ascii=False, encoding='utf8')>>> su'{"1": "u05d1u05e8u05d9 u05e6u05e7u05dcu05d4", "2": "u05d1u05e8u05d9 u05e6u05e7u05dcu05d4"}'>>> json.loads(s)['1']u'u05d1u05e8u05d9 u05e6u05e7u05dcu05d4'>>> json.loads(s)['2']u'u05d1u05e8u05d9 u05e6u05e7u05dcu05d4'>>> print json.loads(s)['1']ברי צקלה>>> print json.loads(s)['2']ברי צקלה


