Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Encoding Custom Types to JSON

Give Feedback

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)

Comments & Discussion

Shay Elmualem on April 2, 2019

In the last snippet: Compex -> Complex, just in case of a copy-paste :)

Thanks.

Dan Bader RP Team on April 2, 2019

Ah, thanks Shay! The typo is fixed now :)

jianpingwu on July 27, 2019

It is very helpful, thanks! How to encode a list of custom objects?

Become a Member to join the conversation.