解决python3 json数据包含中文的读写问题
发布时间:2020-12-16 21:05:54 所属栏目:Python 来源:网络整理
导读:python3 默认的是UTF-8格式,但在在用dump写入的时候仍然要注意:如下 import jsondata1 = { "TestId": "testcase001","Method": "post","Title": "登录测试","Desc": "登录基准测试","Url": "http://xxx.xxx.xxx.xx","InputArg": { "username": "王小丫","p
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": "��СѾ" },"Result": { "errorno": "0" },"TestId": "testcase001","Title": "��¼����","Url": "http://xxx.xxx.xxx.xx" } 在dump的时候也加上ensure_ascii=False,不然会变成ascii码写到文件中,如下: { "Desc": "u767bu5f55u57fau51c6u6d4bu8bd5","username": "u738bu5c0fu4e2b" },"Title": "u767bu5f55u6d4bu8bd5","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数据包含中文的读写问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程小技巧。 您可能感兴趣的文章:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |