Bulletproof json.dump?
J. Pic
jpic at yourlabs.org
Mon Jul 6 10:45:39 EDT 2020
You can achieve round-tripping by maintaining a type mapping in code, for a
single datatype it would look like:
newloads(datetime, newdumps(datetime.now())
If those would rely on __dump__ and __load__ functions in the fashion of
pickle then nested data structures would also be easy:
@dataclass
class YourStruct:
dt = datetime
children = []
@classmethod
def __load__(cls, data):
return cls(
dt=datetime.fromisoformat(data['dt']),
children=[cls.__load__(c) for c in data['children']])
)
def __dump__(self):
return dict(
dt=self.dt.isoformat(),
children=[c.__dump__() for c in self.children],
)
If your datetime is not being loaded from C-code you can even monkey patch
it and add __load__ and __dump__ on it and data round-trip as long as you
keep the type mapping in a method.
More information about the Python-list
mailing list