import pickle
import os
import configparser
import json
config = configparser.ConfigParser()
config.read("base.conf")
base_url = config.get('base_config', 'url')
# f = open(os.path.join(base_url, 'sample.txt'), 'wb')
# pickle.dump(d, f)
# with open(os.path.join(base_url, 'sample.txt'), 'rb') as f:
# d = pickle.load(f)
#
# print(type(d))
class Student(object):
def __init__(self, indexer, name, score):
self.__name = name
self.__indexer = indexer
self.__score = score
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
self.__name = value
@property
def score(self):
return self.__score
@score.setter
def score(self, value):
self.__score = value
@property
def indexer(self):
return self.__indexer
def stu2dict(student):
return {
'name': student.name,
'index': student.indexer,
'score': student.score
}
def dict2stu(dict):
return Student(dict['index'], dict['name'], dict['score'])
d = Student(1, 'feilong', 90)
print('The data before pickling : ', d)
json_str = json.dumps(d, default=stu2dict)
st = json.loads(json_str, object_hook=dict2stu)
st2 = json.loads(json_str)
print('json_str:',json_str)
print(st2)
print(st)
python中如果要传输数据,通常的做法还是利用json格式。事实上,通过这段代码,我们可以看出,python格式转换的机制还是通过dict的第三产物运作的。如果在json.loads中没有定义object_hook,那么就会默认将json格式再次转换成dict字典
python 日常笔记2
最新推荐文章于 2024-11-02 14:33:49 发布