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
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-class-object-to-json-in-python
Convert class object to JSON in Python - GeeksforGeeks
July 23, 2025 - Let's explore different methods to achieve this. Every Python object has a __dict__ attribute that stores its attributes in a dictionary form. By accessing this attribute, you can quickly convert the object's data into a dictionary, which can then be serialized into a JSON string using json.dumps(). This method works well for simple objects but doesn’t give you control over how the object is represented in JSON. ... import json class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("Alice", 30) # Convert object's attributes (__dict__) to JSON res = json.dumps(p1.__dict__) print(res)
Discussions

How can I make this class tree serializable with json?
Depends whether you need to reserialize later. If not you can provide a default conversion function to json.dumps such as json.dumps(obj, default=str) where str is broadly implemented method and therefore a good first choice. As mentioned, if you plan to use json.loads this will not recover the classes as objects, just their string representations. For that it's a little trickier but thoroughly treated on SO. https://stackoverflow.com/questions/3768895/how-to-make-a-class-json-serializable More on reddit.com
🌐 r/learnpython
1
1
July 14, 2021
python - Serializing class instance to JSON - Stack Overflow
I am trying to create a JSON string representation of a class instance and having difficulty. Let's say the class is built like this: class testclass: value1 = "a" value2 = "b" A call to the More on stackoverflow.com
🌐 stackoverflow.com
My first Python library for converting class instances to JSON with a single decorator
Could you compare and contrast with the builtins dataclasses.asdict? >>> from dataclasses import asdict, dataclass >>> @dataclass ... class Person: ... name: str ... surname: str ... >>> person = Person("Avery", "Oliwa") >>> asdict(person) {'name': 'Avery', 'surname': 'Oliwa'} https://docs.python.org/3/library/dataclasses.html#dataclasses.asdict This is the version to use with normal classes: https://docs.python.org/3/library/functions.html#vars More on reddit.com
🌐 r/Python
5
6
March 2, 2022
How to convert JSON data into a Python object? - Stack Overflow
Copydef _json_object_hook(d): return ... x = json2obj(data) If you want it to handle keys that aren't good attribute names, check out namedtuple's rename parameter. ... this may result in a Value error, ValueError: Type names and field names cannot start with a number: '123' 2014-04-11T21:01:38.623Z+00:00 ... As a newbie to Python, I'm interested if this is a save thing also when security is an issue. 2015-07-05T22:15:31.643Z+00:00 ... This creates a new different class each time ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Json2CSharp
json2csharp.com › code-converters › json-to-python
JSON to Python Classes Online Converter - Json2CSharp Toolkit
The next step that needs to be done is mapping each Json node and attributes to Python classes and properties. We can do so by creating a static method in our Python classes that's responsible for mapping our dictionary to our Python properties.
🌐
Medium
medium.com › @life-is-short-so-enjoy-it › python-alternative-how-to-serialize-class-object-to-json-de614210dea2
Python: Alternative: How to Serialize Class Object to JSON | by Life-is-short--so--enjoy-it | Medium
January 2, 2024 - I wanted to see JSON formatted output from CLI module as well, so I tried to JSON-encode by using json.dumps. However, it didn’t work. For example, the sample code will fail since it can’t encode `EMREKSVirtualCluster` import json from typing import List from pydantic import BaseModel class EMREKSVirtualCluster(BaseModel): name: str def get_virtual_clusters() -> List[EMREKSVirtualCluster]: r_value = [ EMREKSVirtualCluster(name="xxx"), EMREKSVirtualCluster(name="yyy"), ] return r_value res = get_virtual_clusters() print(json.dumps(res))
🌐
Python
docs.python.org › 3 › library › json.html
json — JSON encoder and decoder
Identical to load(), but instead of a file-like object, deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table. Changed in version 3.6: s can now be of type bytes or bytearray. The input encoding should be UTF-8, UTF-16 or UTF-32. Changed in version 3.9: The keyword argument encoding has been removed. class json.JSONDecoder(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)¶
🌐
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 - First, let’s define a simple class which we will use to test our serialization and deserialization logic: ... Our User class has 3 fields: name, id and age, and a method named describe that returns a description of the User as String. Let’s try simple approach for serializing and deserializing a User instance: In this solution we are using Python’s json dumps function to serialize the User instance to a JSON String representation and loads function to deserialize the JSON string back to a User instance.
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
This file contains the Json, JsonEncoder and JsonDecoder classes. These classes is all that is needed in order to serialize/deserialize Python objects to/from Json string data.
Author: tbebekis
🌐
Reddit
reddit.com › r/learnpython › how can i make this class tree serializable with json?
r/learnpython on Reddit: How can I make this class tree serializable with json?
July 14, 2021 -

I'm trying to figure out how I can make this json serializable using the json library. I checked online and it looks like all object types must be set to a dictionary, so I set the functions up to cast to dict using dict. I get this error:

TypeError: Object of type builtin_function_or_method is not JSON serializable

Here's some sample code. The code I'm using is also using lists of classes, but I think the principle is the same. How can I cast a python class tree to a json string?

import json

class Child:
    id: int
    value: str
    def __init__(self, id: int,value: str) -> None:
        self.id = id
        self.value = value

class Parent:
    pid: int
    child_obj: Child
    def __init__(self, pid: int,child_obj: Child) -> None:
        self.id = id
        self.child_obj = child_obj
        
def BuildChild(id,value):
    child = Child(id,value)
    return child.__dict__

def BuildParent(child):
    pid = "10"
    parent = Parent(pid,child)
    return parent.__dict__
    
def BuildJson():
    child = BuildChild("4","SomeValue")
    parent = BuildParent(child)
    jstr = json.dumps(parent)
    return jstr

jstr = BuildJson()
print(jstr)
Top answer
1 of 16
322

The basic problem is that the JSON encoder json.dumps() only knows how to serialize a limited set of object types by default, all built-in types. List here: https://docs.python.org/3.3/library/json.html#encoders-and-decoders

One good solution would be to make your class inherit from JSONEncoder and then implement the JSONEncoder.default() function, and make that function emit the correct JSON for your class.

A simple solution would be to call json.dumps() on the .__dict__ member of that instance. That is a standard Python dict and if your class is simple it will be JSON serializable.

class Foo(object):
    def __init__(self):
        self.x = 1
        self.y = 2

foo = Foo()
s = json.dumps(foo) # raises TypeError with "is not JSON serializable"

s = json.dumps(foo.__dict__) # s set to: {"x":1, "y":2}

The above approach is discussed in this blog posting:

    Serializing arbitrary Python objects to JSON using _dict_

And, of course, Python offers a built-in function that accesses .__dict__ for you, called vars().

So the above example can also be done as:

s = json.dumps(vars(foo)) # s set to: {"x":1, "y":2}
2 of 16
96

There's one way that works great for me that you can try out:

json.dumps() can take an optional parameter default where you can specify a custom serializer function for unknown types, which in my case looks like

def serialize(obj):
    """JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, date):
        serial = obj.isoformat()
        return serial

    if isinstance(obj, time):
        serial = obj.isoformat()
        return serial

    return obj.__dict__

First two ifs are for date and time serialization and then there is a obj.__dict__ returned for any other object.

the final call looks like:

json.dumps(myObj, default=serialize)

It's especially good when you are serializing a collection and you don't want to call __dict__ explicitly for every object. Here it's done for you automatically.

So far worked so good for me, looking forward for your thoughts.

🌐
Reddit
reddit.com › r/python › my first python library for converting class instances to json with a single decorator
r/Python on Reddit: My first Python library for converting class instances to JSON with a single decorator
March 2, 2022 -

Hi there! My name's Avery and I've been working with Python for quite some time now. I've been recently working on a game for my girlfriend in Pygame for our 6th anniversary. While working on it I discovered that making a save system is quite troublesome, since I have to save all of the relevant data that is stored using class instances during the gameplay (I decided to use JSON as a save file format).

So that's why I decided to create my own first library that does exactly that, it's a single decorator that you put on a class that you wish to be converted to JSON along with all of its properties (and the nested properties of these properties and so on...)

Here's a short example from the README:

from jsonifable import Jsonifable

# it is not required to use dataclasses
# using them will just make this example shorter
from dataclasses import dataclass


@Jsonifable
@dataclass
class Person:

    name: str
    surname: str


person = Person("Avery", "Oliwa")
jsonified = person.to_json()
print(jsonified)  # {"name": "Avery", "surname": "Oliwa"}

I'm pretty proud of it, and any criticism is more than welcome!

Pypi: https://pypi.org/project/jsonifable/

GitHub: https://github.com/maciejoliwa/jsonifable

🌐
Codemia
codemia.io › knowledge-hub › path › how_to_make_a_class_json_serializable
How to make a class JSON serializable
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
Use the separators parameter to change the default separator: json.dumps(x, indent=4, separators=(".
🌐
PYnative
pynative.com › home › python › json › make a python class json serializable
Make a Python Class JSON Serializable
May 14, 2021 - The EmployeeEncoder class overrides the default() method of a JSONEncoder class, so we able to convert custom Python object into JSON.
🌐
Medium
medium.com › @balakrishnamaduru › how-to-easily-convert-json-into-python-objects-a732ace12011
How to Easily Convert JSON into Python Objects | by Balakrishna Maduru | Medium
October 19, 2024 - While this works fine, dictionaries ... object (or what we’ll call a “sobject”), you can create a class that dynamically loads the JSON fields as attributes....
Top answer
1 of 16
736

UPDATE

With Python3, you can do it in one line, using SimpleNamespace and object_hook:

import json
from types import SimpleNamespace

data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'

# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(data, object_hook=lambda d: SimpleNamespace(**d))
# Or, in Python 3.13+:
#   json.loads(data, object_hook=SimpleNamespace)
print(x.name, x.hometown.name, x.hometown.id)

OLD ANSWER (Python2)

In Python2, you can do it in one line, using namedtuple and object_hook (but it's very slow with many nested objects):

import json
from collections import namedtuple

data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'

# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
print x.name, x.hometown.name, x.hometown.id

or, to reuse this easily:

def _json_object_hook(d): return namedtuple('X', d.keys())(*d.values())
def json2obj(data): return json.loads(data, object_hook=_json_object_hook)

x = json2obj(data)

If you want it to handle keys that aren't good attribute names, check out namedtuple's rename parameter.

2 of 16
208

You could try this:

class User():
    def __init__(self, name, username):
        self.name = name
        self.username = username

import json
j = json.loads(your_json)
u = User(**j)

Just create a new object and pass the parameters as a map.


You can have a JSON with objects too:

import json
class Address():
    def __init__(self, street, number):
        self.street = street
        self.number = number

    def __str__(self):
        return "{0} {1}".format(self.street, self.number)

class User():
    def __init__(self, name, address):
        self.name = name
        self.address = Address(**address)

    def __str__(self):
        return "{0} ,{1}".format(self.name, self.address)

if __name__ == '__main__':
    js = '''{"name":"Cristian", "address":{"street":"Sesame","number":122}}'''
    j = json.loads(js)
    print(j)
    u = User(**j)
    print(u)
🌐
JSON Formatter
jsonformatter.org › json-to-python
Best JSON to Python Converter
JSON to Python Online with https and easiest way to convert JSON to Python. Save online and Share.
🌐
ReqBin
reqbin.com › code › python › pbokf3iz › python-json-dumps-example
How to dump Python object to JSON using json.dumps()?
To dump a Python object to JSON string, you can use the json.dumps() method of the built-in json module.
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-json-data-into-a-custom-python-object
Convert JSON data Into a Custom Python Object - GeeksforGeeks
July 3, 2025 - Explanation: the namedtuple allows us to treat the JSON data as an object, where we can access values by their keys as attributes. We can also write a custom decoder function that converts the JSON dictionary into a custom Python object type, and use this function with json.loads().
🌐
Json2CSharp
json2csharp.com
Convert JSON to C# Classes Online - Json2CSharp Toolkit
When you copy the returned classes in the directory of your solution, you can deserialize your JSON response using the 'Root' class using any deserializer like Newtonsoft.