# 该例子中,Person 是自定义的类,所以调用 dumps 时,如果直接传入,会抛 exception: TypeError: Object of type Person is not JSON serializable classPerson: def__init__(self, name, age): self.name = name self.age = age
# 可以通过指定 default 参数,给出转化规则
defPersonConvert(person): if isinstance(person, Person): return person.__dict__ else: raise TypeError
defdict_to_obj(our_dict): """ Function that takes in a dict and returns a custom object associated with the dict. This function makes use of the "__module__" and "__class__" metadata in the dictionary to know which object type to create. """ if"__class__"in our_dict: # Pop ensures we remove metadata from the dict to leave only the instance arguments class_name = our_dict.pop("__class__") # Get the module name from the dict and import it module_name = our_dict.pop("__module__") # We use the built in __import__ function since the module name is not yet known at runtime module = __import__(module_name) # Get the class from the module class_ = getattr(module,class_name) # Use dictionary unpacking to initialize the object obj = class_.__new__(class_) for key, value in our_dict.items(): if key == 'create_date': value = datetime.fromtimestamp(value) setattr(obj, key, value) else: obj = our_dict return obj