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
Now, we need to read our JSON file and deserialize it. We can use the optional object_hook
argument to specify our decoding function.
with open("complex_data.json") as complex_data:
z = json.load(complex_data, object_hook=decode_complex)
Now, if we print the type of z
, we’ll see
<class 'complex'>
We have now deserialized a complex
object from a JSON file!
Congratulations, you made it to the end of the course! What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment in the discussion section and let us know.
Anonymous 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.