您好,登錄后才能下訂單哦!
序列化: dumps
把內(nèi)存的數(shù)據(jù)結(jié)構(gòu)保存下來(lái)
import json
dic={'a':1}
res1=json.dumps(dic)
re2=str(dic)
print(res1,type(res1)) #json格式都是用的雙引號(hào)
print(res2,type(res2))
x=None
res=json.dumps(x)
print(res,type(res))
import json #把python格式轉(zhuǎn)化為json格式
user={'name':'xiaoxiao','age':18,'ng':True}
with open('user.json','w',encoding='utf-8') as f:
f.write(json.dumps(user))
import json #同上
user={'name':'xiaoxiao','age':18,'ng':True}
json.dump(user,open('user_new.json','w',enccoding='utf-8')) #dump合并成一行
反序列化:loads
import json
with open('user.json','r',encoding='utf-8') as f:
user=json.loads(f.read()) #以json格式讀取文件內(nèi)容
print(user.['name'])
import json
u=json.load(open('user.json','r',encoding='utf-8')) #同上,load合并成一行
print(u['age'])
json_res={"name":'xi'} #json只能用雙引號(hào)
print(json.load(json_res))
pickle:序列化,能支持所有的Python類型,并以byte類型打開(kāi)
improt pickle,json
s={1,2,3,4}
#print(json.dumps(s))
print(pickle.dumps(s))
with open('s.pkl','wb') as f:
f.write(pickle.dumps(s))
pickle.dump(s,open('s.pkl','wb')) #同上
#pickle反序列化
import pickle
with open('s.pkl','rb') as f:
s=pickle.loads(f.read())
print(s,type(s))
s=pickle.load(open('s.pkl','rb')) #同上
print(s,type(s))
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。