解决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标准库--functools.partial

浅谈python标准库--functools.partial

一.简单介绍:  functools模块用于高阶函数:作用于或返回其他函数的函数。一般而言,任何可调用对象都可以作为本模块用途的函数来处理。  functools....

python修改字典键(key)的方法

python修改字典键(key)的方法

python字典中,值可任意更改;但键是唯一的,不支持直接修改。若真的需要修改字典中的键,可通过几种间接方式实现。 新建空白字典。 info = {} 给字典添加键-值对。...

python决策树之C4.5算法详解

python决策树之C4.5算法详解

本文为大家分享了决策树之C4.5算法,供大家参考,具体内容如下 1. C4.5算法简介   C4.5算法是用于生成决策树的一种经典算法,是ID3算法的一种延伸...

python调用c++传递数组的实例

如下所示: INPUT = c_int * 4 # 实例化一个长度为2的整型数组 input = INPUT() # 为数组赋值(input这个数组是不支持迭代的) input[0]...

在Linux下使用Python的matplotlib绘制数据图的教程

在Linux下使用Python的matplotlib绘制数据图的教程

如果你想要在Linxu中获得一个高效、自动化、高质量的科学画图的解决方案,应该考虑尝试下matplotlib库。Matplotlib是基于python的开源科学测绘包,基于python软...