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)


浙公网安备 33010602011771号