json序列化

info = {
    
'name':'alex',
    
'age':22
}

f = 
open("test.txt",'w')
f.write(
str(info)) #把一个字典转换成字符串 从内存存到硬盘的过程叫序列化
f.close()

import json
info = {
    
'name':'alex',
    
'age':22
}

f = 
open("test.txt",'w')
#print(json.dumps(info))
f.write(json.dumps(info)) #把一个字典转换成字符串 从内存存到硬盘的过程叫序列化
f.close()                 #序列化dumps 函数不可以序列化 只能处理简单的跨平台数据交互

import json
info = {
    
'name':'alex',
    
'age':22
}
f = 
open("test.txt","w")
json.dump(info,f)

info[
"age"]=21
json.dump(info,f) #一般只dump一次,因为3.x版本只能load一次,dump多次没意义

f.close()

 

json反序列化

f = open("test.txt",'r')
data = 
eval(f.read())
f.close()
print(data['age'])

import json
f = 
open("test.txt",'r')
data = json.loads(f.read()) 
#反序列化loads
print(data['age'])

import json
f = 
open("test.txt",'r')
#data = json.load(f) #等于data= json.loads(f.read()) 会报错 3.X只能load一次
for line in f:
    
print(line)

 

pickle序列化

import pickle
def sayhi(name):
    
print("hello,",name)

info = {
    
'name':'alex',
    
'age':22,
    
'func':sayhi
}

f = 
open("test.txt",'wb')
#print(pickle.dumps(info))
f.write(pickle.dumps(info)) #pickle可以序列化所有的数据
f.close()

import pickle
def sayhi(name):
    
print("hello,",name)

info = {
    
'name':'alex',
    
'age':22,
    
'func':sayhi
}
f = 
open("test.txt","wb")
pickle.dump(info,f) 
# 等于f.write(pickle.dumps(info))
                    #pickle.dump(
对象,文件)
f.close()

 

pickle反序列化
import pickle
def sayhi(name):
    
print("hello2,",name)

f = 
open("test.txt",'rb')
data = pickle.loads(f.read()) 
#反序列化loads pickle只能用在python里面,java不认
print(data["func"]("alex")) #反序列化只要函数名一样就可以,序列化的是整个的数据对象

import pickle
def sayhi(name):
    
print("hello2,",name)
f=
open("test.txt",'rb')
data = pickle.load(f) 
#等于data= pickle.loads(f.read())
print(data["func"]("alex"))