将json对象转换为python对象
--test.json
json_data=[{'name':'egon','passwd':'123456','re':True},
{'name':'alice','passwd':'1234ds56','re':False}]
class JsonObject:
def __init__(self,d):
self.__dict__=d
with open('test.json','r',encoding='utf8') as f:
data=json.load(f,object_hook=JsonObject)
print(data[0].name)
import json
from collections import OrderedDict
with open('test.json','r',encoding='utf8') as f:
data=json.load(f,object_pairs_hook=OrderedDict)
python类实例序列化为json对象再反序列化为类实例
classes={
'Point':Point
}
def serialize(obj):
d={'__classname__':type(obj).__name__}
d.update(vars(obj))
return d
def userialize_obj(d):
clsname=d.pop('__classname__',None)
if clsname:
cls=classes[clsname]
obj=cls.__new__(cls)
# obj.__dict__=d
for key,val in d.items():
setattr(obj,key,val)
return obj
else:
return d
with open('test1.json','w',encoding='utf8') as f:
json.dump(Point(2,3),f,default=serialize)
with open('test1.json','r',encoding='utf8') as f:
point=json.load(f, object_hook=userialize_obj)
print(point.__dict__)
|