Loading

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 国际」许可协议进行许可。

posted @   eiSouthBoy  阅读(520)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
menu