前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python json 编码(dump/dumps:字典转化为json)、解码(load/loads:json转化为字典)

python json 编码(dump/dumps:字典转化为json)、解码(load/loads:json转化为字典)

作者头像
用户7886150
修改2021-01-19 10:20:33
1.5K0
修改2021-01-19 10:20:33
举报
文章被收录于专栏:bit哲学院

参考链接: python json 1-1:使用json.dump/dumps将JSON写入文件/字符串

python json 编码(dump/dumps:字典转化为json)、解码(load/loads:json转化为字典) 

一般接口传输数据的数据类型都是json,本文主要介绍json的编码、解码、读取等 

1、json 的数据类型 (1)数字(int、float):      jsondata1 = ‘{“age” : 18}’ (2)字符串("")      jsondate2 = ‘{“phone”: “12345654321”}’ (3)逻辑值(true / false)      jsondata3 = ‘{“boolValue”: False}’ (4)null      jsondata4 = ‘{“nullValue”: None}’ (5)对象({})      jsondata5 = ‘{“name” : “yezi”, “address” : { “country”: “china”, “city”: “HeBei” } }’ (6)数组([])      jsondata6 = ‘{“updatedate”: [22, 23, 24]}’ 

2、python 对 json 进行编码、解码 (1)编码:      ① json.dump(): python 对象 --> json字符串,并写入文本文件 

import json

dictdata = {

    "age": 18,

    "phone": "12345654321",

    "boolValue": False,

    "nullValue": None,

    "info": {

        "name" : "yezi",

        "address": {

            "country": "china",

            "city": "HeBei"

        }

    },

    "updatedate": [22, 23, 24]

}

######## 字典 --> json 并写入 txt 文件

with open("jsondata.txt", "w", encoding = "utf-8") as f:

    json.dump(dictdata, f) 

######## 字典 --> json 并写入 json 文件

with open("jsondata.json", "w", encoding = "utf-8") as f:

    json.dump(dictdata, f) 

     ② json.dumps(): python 对象 --> json 字符串 

jsondatas = json.dumps(dictdata)  # 返回结果:'{"age": 18, "phone": "12345654321", "boolValue": false, "nullValue": null, "info": {"name": "yezi", "address": {"country": "china", "city": "HeBei"}}, "updatedate": [22, 23, 24]}'

######## 如果想写入 txt 文件中

with open("jsondatas.txt", "w", encoding = "utf-8") as f:

    f.write(jsondatas) 

######## 如果想写入 json 文件中

with open("jsondatas.json", "w", encoding = "utf-8") as f:

    f.write(jsondatas) 

(2)解码:      ① json.load():读取文件内容 --> python 对象 

######## 从 txt文件读取内容

with open('jsondata.txt','r') as f:

    dictdata = json.load(f)  # 返回结果:{'age': 18, 'phone': '12345654321', 'boolValue': false, 'nullValue': null, 'info': {'name': 'yezi', 'address':{'country': 'china', 'city': 'HeBei'}}, 'updatedate': [22, 23, 24]}

######## 从 json 文件读取内容

with open('jsondata.json','r') as f:

    dictdata = json.load(f)  # 返回结果:{'age': 18, 'phone': '12345654321', 'boolValue': false, 'nullValue': null, 'info': {'name': 'yezi', 'address':{'country': 'china', 'city': 'HeBei'}}, 'updatedate': [22, 23, 24]}

     ② json.loads():字符串 --> python 对象 

dictdata = json.loads(jsondatas)  # 返回结果:{'age': 18, 'phone': '12345654321','boolValue': false, 'nullValue': null, 'info': {'name': 'yezi', 'address': {'country': 'china', 'city': 'HeBei'}}, 'updatedate': [22, 23, 24]}

本文系转载,前往查看

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

本文系转载前往查看

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

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