json & pickle数据序列化
序列化: 就是列表,字典等数据类型转乘字符串存入文本文件
反序列: 就是字符串从文本读出来后通过一种方法转化为列表,字典等数据类型。例如eval()
json通用的:只能处理一些简单的数据类型:
json:
序列化和反序列化函数:
案例1:
import json
info = {
"name": "brace",
"age": 22,
}
json_str = json.dumps(info) #序列化为字符类型
print(type(json_str), json_str)
data = json.loads(json_str) #反序列化为字典类型
print(type(data), data)
输出:
<class ‘str‘> {"name": "brace", "age": 22}
<class ‘dict‘> {‘name‘: ‘brace‘, ‘age‘: 22}
案例2:
import json
info = {
"name": "brace",
"age": 22,
}
with open("data", "w") as fs1:
json.dump(info, fs1) #可以直接序列化后执行文件存储;
with open("data", "r") as fs2:
data = json.load(fs2) #可以直接执行文件读取后反序列化;
print(type(data), data)
输出:
<class ‘dict‘> {‘name‘: ‘brace‘, ‘age‘: 22}
案列3:
import json
a = {5:1,9:2,1:3,8:4,3:9}
with open("data.txt","w") as fs1:
fs1.write(json.dumps(a)) #序列化存储
fs1.flush()
with open("data.txt","r") as fs2:
data = json.loads(fs2.read()) #读取后反序列化
print(data)
{‘5‘: 1, ‘9‘: 2, ‘1‘: 3, ‘8‘: 4, ‘3‘: 9}
pickle:只能在python中使用:
可以执行一些稍复杂的序列化和反序列化
案例 1:
import pickle
def sayHi(name):
print("hello %s" %name)
info = {
"name": "brace",
"age": 22,
"func": sayHi
}
with open("data.txt","wb") as fs1:
fs1.write(pickle.dumps(info)) #pickle.dumps() 转化的时二进制类型。所以必须用wb来存储
fs1.flush()
with open("data.txt","rb") as fs2: #pickle.loads() 读取2进制数据后进行反序列化
data = pickle.loads(fs2.read())
print(data)
输出:
{‘name‘: ‘brace‘, ‘age‘: 22, ‘func‘: <function sayHi at 0x02F6BA08>}
案例2:
pickle的dump和load的方法:和上面的功能时一样的,但可以直接文件操作
import pickle
def sayHi(name):
print("hello %s" %name)
info = {
"name": "brace",
"age": 22,
"func": sayHi
}
with open("data.txt","wb") as fs1:
pickle.dump(info, fs1) #可以直接序列化后执行文件存储;
with open("data.txt","rb") as fs2:
data=pickle.load(fs2) #可以直接执行文件读取后反序列化;
print(data)
输出:
{‘name‘: ‘brace‘, ‘age‘: 22, ‘func‘: <function sayHi at 0x02F6BA08>}
原文地址:https://www.cnblogs.com/brace2011/p/9194079.html