import json
import requests
my_dict = {
'name': 'mxy',
'age': 22,
'friends': ['wdc', 'byf'],
'cars':[
{'brand': 'BMW', 'max_speed': 240},
{'brand': 'Audi', 'max_speed': 280},
{'brand': 'Benz', 'max_speed': 280}
]
}
#将字典处理成JSON格式
print(json.dumps(my_dict))
#将字典处理成json格式并写入文本文件
#只需要将dumps函数换成dump函数并传入文件对象即可
with open('data.json', 'w') as file:
json.dump(my_dict, file)
#反序列化
with open('data.json', 'r') as file:
my_dict = json.load(file)
print(type(my_dict))
print(my_dict)
import requests
resp = requests.get('http://api.tianapi.com/networkhot/index?key=01283528f41c468b8942e7cd2b46ae20')
if resp.status_code == 200:
data_model = resp.json()
for news in data_model['newslist']:
print(news['title'])
print(news['digest'])
print('-' * 60)
Python 对象的序列化和反序列化
最新推荐文章于 2024-01-10 16:28:42 发布