Skip to content
the poor coder

python class json serializable

Poor Man
Published
Reading time
2 min read
On this page

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:#

Text

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:

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC