Is there a convention for JSON-serializing (and deserializing) Python objects to identify the object type? I've gone through this example solution below (which I find quite decent with slight modification), but I still wonder: is any safety concern and is it crystal-clear enough?
Result (Note the addition of the __type__ attribute)
{
"__type__": "date",
"year": 2022,
"month": 1,
"day": 1
}
is printed from the following code:
import json
from datetime import date, timedelta
class MyJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, date):
return {
'__type__' : 'date',
'year' : obj.year,
'month' : obj.month,
'day' : obj.day
}
elif isinstance(obj, timedelta):
return {
'__type__' : 'timedelta',
'days' : obj.days,
'seconds' : obj.seconds,
'microseconds' : obj.microseconds,
}
# And more and more classes to support
else:
return super().default(self, obj)
class MyJSONDecoder(json.JSONDecoder):
SUPPORTING_TYPES = {'date': date, 'timedelta': timedelta}
def __init__(self):
super().__init__(object_hook=self.dict_to_object)
def dict_to_object(self, d):
if '__type__' in d and d['__type__'] in self.SUPPORTING_TYPES:
obj_type = self.SUPPORTING_TYPES[d.pop('__type__')]
return obj_type(**d)
return d
# And to encode / decode
d = date(2022,1,1)
serialized_d = json.dumps(d, cls=MyJSONEncoder)
print(serialized_d)
d_ = json.loads(serialized_d, cls=MyJSONDecoder)
assert d == d_ # Assertion check