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

yipeiwu_com4年前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机器学习理论与实战(四)逻辑回归

         从这节算是开始进入“正规”的机器学习了吧,之所以“正规”因为它开始要建立价值函...

详解Django框架中的视图级缓存

更加颗粒级的缓存框架使用方法是对单个视图的输出进行缓存。 django.views.decorators.cache定义了一个自动缓存视图响应的cache_page装饰器。 他是很容易使...

python实现将一个数组逆序输出的方法

方法一: def printTheReverseArray(self): list_1 = [1, 2, 3, 4, 5, 6, 7] length = len(list_1...

Python 开发Activex组件方法

使用win32com模块开发window ActiveX的示例:(如果你还没有装win32com模块的话,请到http://python.net/crew/skippy/win32/Do...

Python中 map()函数的用法详解

Python中 map()函数的用法详解

map( )函数在算法题目里面经常出现,map( )会根据提供的函数对指定序列做映射,在写返回值等需要转换的时候比较常用。 关于映射map,可以把[ ]转成字符串的话,就不需要用循环打印...