My JSON reads:
{
"employee_1": {"name": "Sarah"},
"employee_2": {"name": "Emma"}
}
Which is created as:
class Employee:
def __init__(self, name):
self.name = name
employees = {}
employees["employee_1"] = Employee("Sarah")
employees["employee_2"] = Employee("Emma")
json_str = json.dumps(employees,
default=lambda x: x.__dict__)
I write this JSON to a file and later on, load it from the file. However, the loaded object is deserialized as a dictionary of dictionaries, rather than a dictionary of Employee
s.
loaded_employees = json.loads(json_str)
print(type(employees["employee_1"]))
print(type(loaded_employees["employee_1"]))
Output is:
<class '__main__.Employee'>
<class 'dict'>
I want the loaded employee_1
to be of type Employee
, exactly as it was when persisting to JSON.
I think this should be achievable leveraging object_hook
; this SO answer or object_hook
documentation explain how to use it for "flat" type object (for the lack of a better word), though not sure how I can use it for a dictionary of custom type as is here.