栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将utf-8文本保存在json.dumps中为UTF8,而不是 u转义序列

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将utf-8文本保存在json.dumps中为UTF8,而不是 u转义序列

使用

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']ברי צקלה


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/415667.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号