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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

眼前的苟且   2021-03-28 我要评论
想了解解决python3 json数据包含中文的读写问题的相关内容吗,眼前的苟且在本文为您仔细讲解python3 json数据包含中文的读写的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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"
}

在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数据包含中文的读写问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们