导语:
本文主要介绍了关于解决python3 json数据包含中文的读写问题的相关知识,包括vbapi读写json,以及python 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"
}
转储的时候还要加上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(':')
本文为原创文章,版权归知行编程网所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ Python基本数据类型和基本操作11/12
- ♥ 如何使用python自带的IDE10/27
- ♥ Python无法连接MySQL怎么办11/13
- ♥ 如何理解整数对象存储在 Python 中的位置?12/15
- ♥ Python单向循环链表的创建01/06
- ♥ Python中的匿名函数是什么11/08
内容反馈