Python处理json文件
Python处理json文件
JSON数据处理类型:
序列化: 将python中的数据类型转换为JSON格式字符串
反序列化:将JSON格式字符串转换为python中的数据类型
json库提供四种方法:json.dumps()
、json.dump()
、json.loads()
、json.load()
1. json.dump()#
将python数据类型写入json文件(案例是将字典写入json文件)
import json
filename = "student.json"
student = {"name":"CC", "age":20, "height":1.75}
with open (filename, 'w') as f:
json.dump(student, f)
2. json.dumps()#
将python数据类型转换成json字符串(案例是将字典转换为字符串)
import json
student = {"name":"CC", "age":20, "height":1.75}
student_json = json.dumps (student)
print (type(student_json))
print (student_json)
3. json.load()#
将json文件读入,存放到python数据类型(案例是读取json文件,返回对象类型是字典)
import json
filename = "student.json"
with open (filename , 'r') as f:
students = json.load (f)
print (type (students))
print (students)
4. json.loads()#
将字符串转换为python数据类型(案例是将字符串转换为字典)
import json
student_str = "{\"name\":\"CC\", \"age\":20, \"height\":1.75}"
student_dict = json.loads (student_str)
print (type(student_dict))
print (student_dict)
作者:caojun97
出处:https://www.cnblogs.com/caojun97/p/16244193.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix