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.
Hint: You can set the default subtitles language 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.

JSON for Custom Python Objects

Give Feedback

In this video you’ll learn how to work with types that are non-serializable.

The json module is not capable of serializing all Python types. Non-serializable types include custom types created from classes, as well as the built-in complex type used to represent imaginary numbers.

json_str = json.dumps(6 + 2j)  # cannot serialize complex object

In order to serialize these types, we must extract the necessary data to recreate the object.

The complex type stores both the real and imaginary parts of the complex number as float. Floats are a type that can be serialized by the dump() and dumps() methods. In the next video, you’ll learn how to encode them into JSON format.

terrymiddleton on May 11, 2019

So…after a little Google searching on serialize and deserialize of json, it has become apparent that the process of serializing and deserializing is simply taking a json object and converting it to a string that can be worked with.

Is this correct.

With an object, it has a certain structure and framework that does not work well/properly with evaluating or working with strings. An output to a file has to be put in a string format so it can be written, while the data may reside in an object.

For example, if I wanted to write out all the books in a certain library and all the books were sitting in an object called library, I would need to “convert” all the books within the object to a string so I could write it to a file or work with it in code.

Am I thinking correctly on this? Terry

Abby Jones on June 28, 2019

I think it is more involved than that, but I am not sure how. I am still learning as well.

Arjun Umathanu on Oct. 7, 2020

import json

class Person:

    def __init__(self, name, age): = name
        self.age = age
        self.alive = True

    def serialize(self):
        return {'name':, 'age': self.age, 'alive': self.alive}
>>> json_str = json.dumps(Person('Will', 29).serialize())
>>> print(json_str)
{"name": "Will", "age": 29, "alive": true}  # output :D

Become a Member to join the conversation.