前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python3 json数据包含中文的读

python3 json数据包含中文的读

作者头像
py3study
发布2020-01-13 15:30:54
7630
发布2020-01-13 15:30:54
举报
文章被收录于专栏:python3

python3 默认的是UTF-8格式,但在在用dump写入的时候仍然要注意:如下

代码语言:javascript
复制
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’,不然会显示成乱码,如下:

代码语言:javascript
复制
{
    "Desc": "��¼��׼����",
    "InputArg": {
        "passwd": "123456",
        "username": "��СѾ"
    },
    "Method": "post",
    "Result": {
        "errorno": "0"
    },
    "TestId": "testcase001",
    "Title": "��¼����",
    "Url": "http://xxx.xxx.xxx.xx"
}

在dump的时候也加上ensure_ascii=False,不然会变成ascii码写到文件中,如下:

代码语言:javascript
复制
{
    "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’,不然也是乱码,如下:

代码语言:javascript
复制
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(':')
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/08/13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档