In this video, you’ll learn how to deserialize a non-serializable type given in a JSON file.
We can represent a complex object in JSON like this
{
"__complex__": true,
"real": 42,
"imaginary": 36
}
If we let the load() method deserialize this, we’ll get a Python dict instead of our desired complex object. That’s because JSON objects deserialize to Python dict. We can write a custom decoder function that will read this dictionary and return our desired complex object.
def decode_complex(dct):
if "__complex__" in dct:
return complex(dct["real"], dct["imaginary"])
else:
return dct
techsukenik on Sept. 1, 2021
When serialize/de-serialize heterogenous objects (i.e. Person, Student) how do I avoid having one encoder/decoder function? This will allow new encoder/decoder functions for new classes without changing the code of a router type decoder/encoder function.
Is it possible to bypass the default encoder option and directly have Python have the encoder function?