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

yipeiwu_com6年前Python基础

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数据包含中文的读写问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python中矩阵创建和矩阵运算方法

Python中矩阵创建和矩阵运算方法

矩阵创建 1、from numpyimport *; a1=array([1,2,3]) a2=mat(a1) 矩阵与方块列表的区别如下: 2、data2=mat(ones((2,4)...

Python字典循环添加一键多值的用法实例

循环写入字典key、value、删除指定的键值对: 原文本‘jp_url.txt'每行元素以逗号分隔: host_key,product_id,product_name,cont_s...

python自动登录12306并自动点击验证码完成登录的实现源代码

以下代码可自动登录12306 - 包括输入用户名密码以及自动识别验证码并点击验证码登陆。该源码需要稍作修改: 把  username.send_keys('xxxxxxx')&...

Python Requests模拟登录实现图书馆座位自动预约

本文实例为大家分享了Python实现图书馆座位自动预约的具体代码,供大家参考,具体内容如下 配置 通过公网主机定时运行脚本,并发送邮件到自己的qq邮箱,这样在微信就会有消息提示是否预约成...

Python导出数据到Excel可读取的CSV文件的方法

本文实例讲述了Python导出数据到Excel可读取的CSV文件的方法。分享给大家供大家参考。具体实现方法如下: import csv with open('eggs.csv', '...