python中,json和pickle
都是可以序列化的方式,但是不同的是,json是公用的,即所有语言都可以使用,但是pickle仅仅在python内部才能使用。
两者拥有相同的方法,作用也是相同的,但是json只能序列化像字符串
,字典
,列表
等这些简单的数据类型,因为python里有的,其他语言里不一定有,所以,只有大部分的语言都有的,并且类型相同的数据类型,json才会有。
dumps、dump、loads、load
dumps、dump、loads、load
json的序列化与反序列化
import json
info = {
"name":"DuZhaoqi","age":23}
f = open("infomation.txt","w",encoding="utf-8")
f.write(json.dumps(info)) #序列化
import json
f = open("infomation.txt","r",encoding="utf-8")
data = json.loads(f.read()) #反序列化
print(data)
print(data["age"])
pickle的序列化与反序列化
因为pickle的读写都是用的为二进制,所以,我们需要使用 wb
和 rb
import pickle
def sayhi(name):
print("Hello,",name)
info = {
"name":"DuZhaoqi", "age":23,"func":sayhi}
f = open("infomation.txt","wb")
f.write(pickle.dumps(info)) #序列化
f.close()
import pickle
def sayhi(name):
print("Hello,",name)
print("hello".upper(),name)
info = {
"name":"DuZhaoqi","age":23}
f = open("infomation.txt","rb")
data = pickle.loads(f.read()) #反序列化
print(data)
print(data["age"])
print(data["func"]("Tom"))
除了dumps
和loads
,还可以使用dump
和load
,我用pickle来演示,效果都是一样的
import pickle
def sayhi(name):
print("Hello,",name)
info = {
"name":"DuZhaoqi", "age":23,"func":sayhi}
f = open("infomation.txt","wb")
pickle.dump(info,f) #f.write(pickle.dumps(info))
f.close()
import pickle
def sayhi(name):
print("Hello,",name)
print("hello".upper(),name)
info = {
"name":"DuZhaoqi","age":23}
f = open("infomation.txt","rb")
data = pickle.load(f) #data = pickle.loads(f.read()) #反序列化
print(data)
print(data["age"])
print(data["func"]("Tom"))
注意:在python2中,json可以多次
dump
和loads
,但是在python3中,json可以多次dumps
,但是不能多次loads
了,这一点需要注意。