I have a few custom dataclasses I want to serialize and save within a networkx graph. But I also want to save the class definitions alongside the serialized JSON string so I can deserialize them back into those objects.
These can be nested custom objects, for example:
@dataclass(frozen=True)
class Fruit:
name: str
color: str
picked_on: dt.datetime
@dataclass(frozen=True)
class Apple(Fruit):
orchard: str
Then the serialized data would look something like
dumped = json.dumps(json_graph.node_link_data(<graph with Apples/Fruits>)
I plan on saving the dumped
data into a JSON file, but I also need to snapshot what the dataclasses look like at the moment so I can deserialize that JSON file with that version of the dataclass. This is because the dataclass could change over time and I want to retrieve the graph at any moment in time.
Is there a good way to do the deserialization like that? How would I save the dataclass definitions alongside the actual data?
So I'd like to also save a file somewhere with a JSON mapping something like
{"Fruit": {"name": str, "color": str, "picked_on": dt.datetime}, "Apple": {"parent": "Fruit", "orchard": str}}