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]}
想知道更多,请关注我的公众号~