python class json serializable

Python Class JSON Serializable

When working with Python, one often comes across the need to serialize objects into JSON format. However, not all objects can be serialized directly. This is where the concept of JSON serializable comes into play.

In order to make a Python class JSON serializable, you need to define the __dict__ method for the class. This method returns a dictionary representation of the object, which can then be serialized using the json.dumps() function.

Example:


import json

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
  
    def __dict__(self):
        return {
            'name': self.name,
            'age': self.age
        }

p = Person('John', 30)
json_str = json.dumps(p.__dict__)
print(json_str) # {"name": "John", "age": 30}

In the example above, we define a simple class Person with two attributes: name and age. We then define the __dict__ method for the class, which returns a dictionary representation of the object.

We then create an instance of the class p, and serialize it into a JSON string using the json.dumps() function. The resulting JSON string contains the name and age attributes of the object.

Alternative Method:

An alternative method for making a Python class JSON serializable is to use the JSONEncoder class. This class provides a default method for encoding objects into JSON format, and can be subclassed to provide custom encoding for specific classes.

Example:


import json

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
class PersonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Person):
            return {
                'name': obj.name,
                'age': obj.age
            }
        return super().default(obj)

p = Person('John', 30)
json_str = json.dumps(p, cls=PersonEncoder)
print(json_str) # {"name": "John", "age": 30}

In this example, we define the same Person class as before, but we also define a custom PersonEncoder subclass of JSONEncoder.

We then create an instance of the Person class p, and serialize it into a JSON string using the json.dumps() function with the cls argument set to our custom encoder.

The resulting JSON string is identical to the previous example.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe