Fix jsonencoder

This commit is contained in:
Suwako Moriya 2020-03-31 10:31:05 +02:00
parent 2738508875
commit 4c6a2d0685
Signed by: SuwakoMmh
GPG Key ID: A27482B806F13CD5
2 changed files with 15 additions and 16 deletions

View File

@ -5,23 +5,13 @@ data_type = "__data_type"
content = "__content"
class Encoder(json.JSONEncoder):
def __init__(self):
super().__init__()
self.custom = {}
class Encoder():
def __init__(self, *args, **kwargs):
self.custom = {Encoder:(lambda x:x, lambda x:x)}
self.JSONEncoder.custom = self.custom
def register(self, type_, encode, decode):
self.custom.update({type_: (encode, decode)})
def default(self, obj):
if isinstance(obj, tuple(self.custom.keys())):
return {data_type: f'{type(obj)}', content: self.custom[type(obj)][0](obj)}
if isinstance(obj, (datetime.datetime)):
return {data_type: 'datetime.datetime', 'iso': obj.isoformat()}
if isinstance(obj, (datetime.timedelta)):
return {data_type: 'datetime.timedelta', 'totalseconds': obj.total_seconds()}
return json.JSONEncoder.default(self, obj)
def hook(self, dct):
if data_type in dct:
for ty in self.custom.keys():
@ -32,3 +22,12 @@ class Encoder(json.JSONEncoder):
elif dct[data_type] == "datetime.timedelta":
return datetime.timedelta(seconds=dct['totalseconds'])
return dct
class JSONEncoder(json.JSONEncoder) :
def default(self, obj):
if isinstance(obj, tuple(self.custom.keys())):
return {data_type: f'{type(obj)}', content: self.custom[type(obj)][0](obj)}
if isinstance(obj, (datetime.datetime)):
return {data_type: 'datetime.datetime', 'iso': obj.isoformat()}
if isinstance(obj, (datetime.timedelta)):
return {data_type: 'datetime.timedelta', 'totalseconds': obj.total_seconds()}
return json.JSONEncoder.default(self, obj)

View File

@ -8,12 +8,12 @@ class Objects:
def __init__(self, path: str):
self.path = os.path.abspath(path)
os.makedirs(os.path.join(self.path, "objects"), exist_ok=True)
self.encoder = jsonencoder.Encoder
self.encoder = jsonencoder.Encoder()
def save_object(self, object_name, object_instance):
"""Save object into json file"""
with open(os.path.join(self.path, "objects", object_name + ".json"), "w") as file:
json.dump(object_instance, file, cls=self.encoder)
json.dump(object_instance, file, cls=self.encoder.JSONEncoder)
def load_object(self, object_name):
"""Load object from json file"""