解决python3 json数据包含中文的读写问题

作者:眼前的苟且 时间:2022-07-22 03:04:51 

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(':')

来源:https://blog.csdn.net/sunshy2008/article/details/54929563

标签:python,json,包含,中文
0
投稿

猜你喜欢

  • css闭合浮动元素

    2008-05-09 19:41:00
  • php 图片上添加透明度渐变的效果

    2023-10-23 09:00:02
  • python实现通讯录系统

    2023-06-12 20:57:50
  • asp如何实现网络打印?

    2010-05-24 18:31:00
  • Access数据库用另一种方式管理密码

    2008-10-13 12:25:00
  • MySQL 数据编码 latin1 转 UTF8

    2010-10-14 14:20:00
  • Python类属性的延迟计算

    2023-07-22 15:50:33
  • php处理json格式数据经典案例总结

    2023-11-21 13:54:42
  • 白鸦:贪守米缸者,饿死灶台

    2009-02-23 13:03:00
  • 抛砖引玉Web2.0设计指南

    2008-06-30 12:49:00
  • Python 遍历列表里面序号和值的方法(三种)

    2022-11-29 14:01:06
  • Python3.x+pyqtgraph实现数据可视化教程

    2023-09-25 23:24:47
  • pandas中DataFrame重置索引的几种方法

    2023-06-10 00:26:45
  • Python SDK实现私服上传下载的示例

    2021-11-22 08:14:42
  • SQL Server正则表达式 替换函数应用详解

    2023-07-07 23:53:13
  • Python实现自动化刷抖音的实例

    2023-07-20 19:16:15
  • python数据操作之lambda表达式详情

    2022-08-19 21:21:32
  • XML教程:什么是XML及XML和HTML的区别

    2008-09-05 17:21:00
  • sublime text配置node.js调试(图文教程)

    2023-07-04 14:07:57
  • js调用flash代码

    2010-01-23 12:35:00
  • asp之家 网络编程 m.aspxhome.com