Here is a simple solution for a simple feature:

.toJSON() Method

Instead of a JSON serializable class, implement a serializer method:

import json

class Object:
    def toJSON(self):
        return json.dumps(
            self,
            default=lambda o: o.__dict__, 
            sort_keys=True,
            indent=4)

So you just call it to serialize:

me = Object()
me.name = "Onur"
me.age = 35
me.dog = Object()
me.dog.name = "Apollo"

print(me.toJSON())

will output:

{
    "age": 35,
    "dog": {
        "name": "Apollo"
    },
    "name": "Onur"
}

For a fully-featured library, you can use orjson.

Answer from Onur Yıldırım on Stack Overflow
🌐
PYnative
pynative.com › home › python › json › make a python class json serializable
Make a Python Class JSON Serializable
May 14, 2021 - We used the use default argument of json.dumps() method to serialize additional types to dict and converted newly created dict to JSON string. Note: Refer to decode JSON into the Custom Python Object instead of a dictionary if you also want to decode JSON back to the Custom Python Object.
Discussions

JSON Serialization
Maybe try orjson instead of the standard library json module. It performs well on benchmarks and has some nice features for encoding stuff like Dataclasses. More on reddit.com
🌐 r/Python
77
101
March 15, 2024
Introduce a __json__ magic method - Ideas - Discussions on Python.org
I’ve often felt that the current CustomEncoder approach to adding custom JSON serialization is a bit of an anti-pattern. The separation of class and serialization logic means that most libraries that wish to output json must also expose a parameter for overriding the default encoder, which ... More on discuss.python.org
🌐 discuss.python.org
11
December 8, 2022
Problems getting url. TypeError: Object of type Series is not JSON serializable
I’m having trouble looping through a list and visiting urls (with selenium) - but this is a basic python problem. I’m still learning. I’ve imported a Google Sheet using the service api. following this tutorial: ----- code -------- from googleapiclient.discovery import build from google.oauth2 ... More on discuss.python.org
🌐 discuss.python.org
1
0
February 21, 2022
Why are python dataclasses not JSON serializable?
Perhaps the problem is that people might be surprised to find that the deserializing does not create the data classes again properly. More on reddit.com
🌐 r/Python
158
212
January 10, 2024
🌐
Python
docs.python.org › 3 › library › json.html
json — JSON encoder and decoder
Extensible JSON encoder for Python data structures. Supports the following objects and types by default: Changed in version 3.4: Added support for int- and float-derived Enum classes.
🌐
Reddit
reddit.com › r/python › json serialization
r/Python on Reddit: JSON Serialization
March 15, 2024 -

I have been using more and more of Python over the past few weeks because I got sick of JS. When I asked a programmer friend of mine who uses JS religiously what he thought about using Python for web backends, he told me that it would be slow because of JSON serialization.

I spent some time researching this, but couldn’t find anything decisive that explained why JSON serialization would be faster in JS. The answers I found said a few things:

  • V8 is optimized for this because it’s part of the JS standard

  • it’s slow in Python because of an implementation of how the JSON to Python representation (JSON dump) function is represented in Python.

Does anyone else have any further insight on this topic? I am trying to understand this at a fundamental level and cut through any noise / wrong understanding.

Thanks so much!

🌐
GeeksforGeeks
geeksforgeeks.org › python › serializing-json-data-in-python
Serializing JSON data in Python - GeeksforGeeks
July 23, 2025 - Serialization is the process of converting Python objects into JSON-compatible data.
🌐
DevGenius
blog.devgenius.io › can-python-do-type-safe-json-serialization-77e4d73ccd08
Can Python do type safe JSON serialization? | by Orrbenyamini | Dev Genius
August 25, 2022 - We can leverage python **kwargs ... the dict returned from json.loads call ... serialize — We use json.dumps to serialize the User instance to JSON String and then json.loads to deserialize it as JSON dictionary...
Find elsewhere
🌐
GitHub
github.com › tbebekis › Python-Json
GitHub - tbebekis/Python-Json: A solution on how to serialize/deserialize objects (and complex objects) in Python · GitHub
In case of an import error regarding the dateutil.parser use pip install python-dateutil · import inspect import json from datetime import date from datetime import datetime from dateutil import parser class Json(object): """ WARNING: do NOT use data-classes, i.e. classes marked with the @dataclass attribute. Use plain classes with an initializer for fields/properties """ def Serialize(Instance): """ Serializes a specified instance and returns the json text formatted """ return json.dumps(Instance, cls=JsonEncoder, indent=4) def Deserialize(JsonText: str, ClassOrInstance = None): """ Deserializes a specified json text.
Author: tbebekis
🌐
Medium
medium.com › @romoon1 › tip-your-variable-type-is-not-json-serializable-with-json-dump-7004cb0e5893
Tip: Your variable type is not JSON serializable with json.dump? | by Romoon | Medium
January 5, 2023 - # With python json package you have the possibility to overwrite the JSON # encoder to define your custom serialization class ComplexEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Point): return (obj[0], obj[1]) # Let the base class default method raise the TypeError return json.JSONEncoder.default(self, obj) def store_json_file(self, name, data): with open(name, "w") as f: json.dump(data, f, cls=ComplexEncoder)
🌐
Python.org
discuss.python.org › ideas
Introduce a __json__ magic method - Ideas - Discussions on Python.org
December 8, 2022 - I’ve often felt that the current CustomEncoder approach to adding custom JSON serialization is a bit of an anti-pattern. The separation of class and serialization logic means that most libraries that wish to output json must also expose a parameter for overriding the default encoder, which ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › serialize-and-deserialize-complex-json-in-python
Serialize and Deserialize complex JSON in Python - GeeksforGeeks
August 11, 2025 - Deserialization means converting that stored or transmitted JSON back into a Python object using json.loads(). Let’s understand this with an examples. When data stored in a Python object only contains basic types (strings, numbers, booleans, etc.), it can be easily serialized and deserialized using Python’s built-in json module and object’s __dict__ attribute.
🌐
Codemia
codemia.io › home › knowledge hub › how to make a class json serializable
How to make a class JSON serializable | Codemia
December 28, 2024 - However, it doesn't know how to ... such cases. To make a custom class JSON serializable, you need to provide a method for converting instances of the class to a form that can be encoded into JSON....
🌐
DevGenius
blog.devgenius.io › jsonic-python-serialization-that-just-works-3b38d07c426d
Jsonic: Python Serialization That Actually Just Works | by Orr Benyamini | Dev Genius
January 5, 2026 - This gives you access to class-level configurations like transient_attributes, allowing you to define once and for all which fields the serializer should ignore. from jsonic import Serializable class User(Serializable): # These fields will be ignored by the serializer every time transient_attributes = ['password_hash', '_cache'] def __init__(self, username: str, password_hash: str): super().__init__() self.username = username self.password_hash = password_hash self._cache = {}
🌐
LearnPython.com
learnpython.com › blog › object-serialization-in-python
Object Serialization in Python | LearnPython.com
Reasons to choose this method over the pickle module include that it’s standardized and language-independent. It is also much more secure and is human-readable. The json module can be used to serialize objects in Python.
🌐
Pydantic
docs.pydantic.dev › latest › concepts › serialization
Serialization | Pydantic Docs
Pydantic allows models (and any other type using type adapters) to be serialized in two modes: Python and JSON.
🌐
PYnative
pynative.com › home › python › json › python json serialize set
Python JSON Serialize Set
February 24, 2024 - Python json module provides a JSONEncoder to encode python types into JSON. We can extend by implementing its default() method that can JSON serializable set.
🌐
Python.org
discuss.python.org › python help
Problems getting url. TypeError: Object of type Series is not JSON serializable - Python Help - Discussions on Python.org
I’m having trouble looping through a list and visiting urls (with selenium) - but this is a basic python problem. I’m still learning. I’ve imported a Google Sheet using the service api. following this tutorial: ----- code -------- from googleapiclient.discovery import build from google.oauth2 import service_account import pandas as pd import time from selenium import webdriver from selenium.webdriver.chrome.service import Service SERVICE_ACCOUNT_FILE = ‘keys.json’ SCOPES =...
Published: February 21, 2022
🌐
Python
docs.python.org › 3 › library › pickle.html
pickle — Python object serialization
The json module: a standard library module allowing JSON serialization and deserialization.
🌐
PyPI
pypi.org › project › serializejson
serializejson · PyPI
serializejson is a python library for fast serialization and deserialization of python objects in JSON designed as a safe, interoperable and human-readable drop-in replacement for the Python pickle package.
🌐
Mark Needham
markhneedham.com › blog › 2017 › 03 › 19 › python-3-typeerror-object-type-dict_values-not-json-serializable
Python 3: TypeError: Object of type 'dict_values' is not JSON serializable | Mark Needham
March 19, 2017 - >>> json.dumps(list(x.values())) '[{"name": "Mark"}, {"name": "Michael"}]' This versions works with Python 2.7 as well so if I accidentally run the script with an old version the world isn’t going to explode.