序列化和反序列化

一 json注意点
# json格式不能识别单引号,全都是双引号

import json

# with open('db1.json','rt',encoding='utf-8') as f:
# json.load(f)

# json.loads('{"name":"egon"}')

# with open('db.json','wt',encoding='utf-8') as f:
# l=[1,True,None]
# json.dump(l,f)

# 用json反序列化
# with open('db.json','rt',encoding='utf-8') as f:
# l=json.load(f)
# print(l)

# 用eval反列化
# with open('db.json','rt',encoding='utf-8') as f:
# s=f.read() #s ='[1, true, null]'
# dic=eval(s) #eval('[1, true, null]')
# print(dic['name'])

二  json的反序列化
import json

#反序列化:中间格式json-----》内存中的数据类型

# #1、从文件中读取json_str
# with open('db.json','rt',encoding='utf-8') as f:
# json_str=f.read()
# #2、将json_str转成内存中的数据类型
# dic=json.loads(json_str)

#1和2可以合作一步
with open('db.json','rt',encoding='utf-8') as f:
dic=json.load(f)

print(dic['sex'])

三  json的序列化
import json

dic={'name':'egon','age':18,'sex':'male'}
#序列化:内存中的数据类型------>中间格式json

# # 1、序列化得到json_str
# json_str=json.dumps(dic)
# # 2、把json_str写入文件
# with open('db.json','wt',encoding='utf-8') as f:
# f.write(json_str)

#1和2合为一步
with open('db.json','wt',encoding='utf-8') as f:
json.dump(dic,f)


# print(json_str,type(json_str)) # json格式不能识别单引号,全都是双引号

四  pickle反序列化
import pickle


# # #1、从文件中读取pickle格式
# with open('db.pkl','rb') as f:
# pkl=f.read()
# #2、将json_str转成内存中的数据类型
# dic=pickle.loads(pkl)
# print(dic['a'])

#1和2可以合作一步
# with open('db.pkl','rb') as f:
# dic=pickle.load(f)
#
# print(dic['a'])


import json,pickle

s={1,2,3}
# json.dumps(s)
pickle.dumps(s)

五 pickle序列化
import pickle

dic={'a':1,'b':2,'c':3}

# #1 序列化
# pkl=pickle.dumps(dic)
# # print(pkl,type(pkl))
#
# #2 写入文件
# with open('db.pkl','wb') as f:
# f.write(pkl)

#1和2可以合作一步
# with open('db.pkl','wb') as f:
# pickle.dump(dic,f)
 








 
posted @ 2018-09-22 01:01  不沉之月  阅读(111)  评论(0编辑  收藏  举报