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
James Magruder on March 30, 2019
This was excellent!! However, it will take me a while to absorb it all. I may have to watch it again.