In this video, you’ll learn how to encode non-serializable types into JSON.
The dump()
and dumps()
methods allow us to include an optional argument default
. Here, we can specify a custom function that will break our non-serializable type down into a serializable object containing the data that’s needed to re-construct it later.
json_str = json.dumps(4+6j, default=complex_encoder)
Now we need to define complex_encoder()
, which will convert our complex
object into a tuple
(which is serializable)
def complex_encoder(z):
if isinstance(z, complex):
return (z.real, z.imag)
else:
type_name = z.__class__.__name__
raise TypeError(f"Object of type {type_name} is not serializable")
We could also achieve this by subclassing json.JSONEncoder
class ComplexEncoder(json.JSONEncoder):
def default(self, z):
if isinstance(z, complex):
return (z.real, z.imag)
else:
return super().default(z)
If we choose this method instead, default
wont work. We need to use cls
instead.
json_str = json.dumps(4+6j, cls=ComplexEncoder)
Shay Elmualem on April 2, 2019
In the last snippet: Compex -> Complex, just in case of a copy-paste :)
Thanks.