analytics, information, innovation-3088958.jpg

Making a python class easy serializable to json

When searching around the web on how to serialize a python class to json I found no easy and clean solution. So here is my best and cleanest solution for python3.

#!/usr/bin/env python3

import json
from dataclasses import dataclass

@dataclass
class Person:
    first: str
    last: str
    age: int

    @property
    def __json__(self):
        return {
            "name": f"{self.first} {self.last}",
            "age": self.age
        }

john = Person("John", "Doe", 42)
print(json.dumps(john, indent=4, default=lambda x: x.__json__))Code language: Python (python)

This way you could also serialize nested classes, as __json__ returns a python object and not a string. No need to use a JSONEncoder, as the default parameter with a simple lambda also works fine.

I’ve used @property instead of a simple function, as this feels more natural and modern. The @dataclass is also just an example, it works for a “normal” class as well.

I’ve also posted this solution on stackoverflow, and I really do not understand why nobody found this simple and clean solution earlier. But I guess most people would not scroll down to my answer. Upvote it, if you like.

Buy Me A Coffee

Leave a Comment

Your email address will not be published. Required fields are marked *