Python Principles
Python Q&A

How do you JSON-serialize a class in Python?

Answer:

If you try to call json.dumps on an object to turn it into a JSON string, you will get the following error:

Traceback (most recent call last):
TypeError: <__main__.Object instance at 0x7f1cb4274b48> is not JSON serializable

To make such an object serializable, the easiest solution is to use the __dict__ attribute that all Python objects have. This attribute represents the instance variables as a dictionary.

We can use this to write a function to convert an object to JSON:

import json

def to_json(obj):
    return json.dumps(obj, default=lambda obj: obj.__dict__)

This uses json.dumps while giving a lambda function as the default named parameter. The lambda function simply uses obj.__dict__ if the obj object otherwise cannot be serialized.

Say that we have this class:

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

If we try to serialize it with the JSON module:

d = Dog("Max", 6)
print(json.dumps(d))

We get an error. But calling to_json on the object works:

>>> d = Dog("Max", 6)
>>> print(to_json(d))
{"age": 6, "name": "Max"}