python json编码(dump/dumps:字典转化为json)、解码(load/loads: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]}

想知道更多,请关注我的公众号~
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值