解决python3 json数据包含中文的读写问题
更新时间:2018年05月10日 16:27:02 作者:眼前的苟且
今天小编就为大家分享一篇解决python3 json数据包含中文的读写问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
python3 默认的是UTF-8格式,但在在用dump写入的时候仍然要注意:如下
import json
data1 = {
"TestId": "testcase001",
"Method": "post",
"Title": "登录测试",
"Desc": "登录基准测试",
"Url": "http://xxx.xxx.xxx.xx",
"InputArg": {
"username": "王小丫",
"passwd": "123456",
},
"Result": {
"errorno": "0"
}
}
with open('casedate.json', 'w', encoding='utf-8') as f:
json.dump(data1, f, sort_keys=True, indent=4)
在打开文件的时候要加上encoding=‘utf-8',不然会显示成乱码,如下:
{
"Desc": "��¼������",
"InputArg": {
"passwd": "123456",
"username": "��СѾ"
},
"Method": "post",
"Result": {
"errorno": "0"
},
"TestId": "testcase001",
"Title": "��¼����",
"Url": "http://xxx.xxx.xxx.xx"
}
在dump的时候也加上ensure_ascii=False,不然会变成ascii码写到文件中,如下:
{
"Desc": "\u767b\u5f55\u57fa\u51c6\u6d4b\u8bd5",
"InputArg": {
"passwd": "123456",
"username": "\u738b\u5c0f\u4e2b"
},
"Method": "post",
"Result": {
"errorno": "0"
},
"TestId": "testcase001",
"Title": "\u767b\u5f55\u6d4b\u8bd5",
"Url": "http://xxx.xxx.xxx.xx"
}
另外python3在向txt文件写中文的时候也要注意在打开的时候加上encoding=‘utf-8',不然也是乱码,如下:
with open('result.txt', 'a+', encoding='utf-8') as rst:
rst.write('return data')
rst.write('|')
for x in r.items():
rst.write(x[0])
rst.write(':')
以上这篇解决python3 json数据包含中文的读写问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
python3.6+opencv3.4实现鼠标交互查看图片像素
这篇文章主要为大家详细介绍了python3.6+opencv3.4实现鼠标交互查看图片像素,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2018-02-02
matplotlib之pyplot模块添加文本、注解(text和annotate)
matplotlib是python最著名的绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地行制图,下面这篇文章主要给大家介绍了关于matplotlib之pyplot模块添加文本、注解(text和annotate)的相关资料,需要的朋友可以参考下2022-05-05
python应用程序在windows下不出现cmd窗口的办法
这篇文章主要介绍了python应用程序在windows下不出现cmd窗口的办法,适用于python写的GTK程序并用py2exe编译的情况下,需要的朋友可以参考下2014-05-05


最新评论