您当前的位置:首页 > IT编程 > python
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:解决python3 json数据包含中文的读写问题

51自学网 2021-10-30 22:41:46
  python
这篇教程解决python3 json数据包含中文的读写问题写得很实用,希望能帮到您。

python3 默认的是UTF-8格式,但在在用dump写入的时候仍然要注意:如下

import jsondata1 = { "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数据包含中文的读写与乱码问题请查看下面的相关链接


Python中selenium库的用法详解
Python Excel处理库openpyxl详解
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。