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.

Answer from DS. 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)
🌐
Python Examples
pythonexamples.org › convert-python-class-object-to-json
Python - Convert Class Object to JSON
Python - Convert Object to JSON - To convert a Python Class Object to JSON String, or save the parameters of the class object to a JSON String, use json.dumps() method.
People also ask

How do I convert a Python object to JSON?
For dataclasses, use dataclasses.asdict(): from dataclasses import asdict; import json; json.dumps(asdict(obj)). For Pydantic models: obj.model_dump_json() (Pydantic v2) or obj.json() (Pydantic v1). For custom classes, implement a default function: json.dumps(obj, default=lambda o: o.__dict__).
🌐
jsonswitcher.com
jsonswitcher.com › jsonshift › json to python › python to json
Convert Python to JSON — Generate Mock Data & Snippets
Is the Python to JSON converter free?
Yes, completely free. No file size limits, no account required. JSONshift is funded by non-intrusive display advertising.
🌐
jsonswitcher.com
jsonswitcher.com › jsonshift › json to python › python to json
Convert Python to JSON — Generate Mock Data & Snippets
How do I convert a Python dataclass to JSON?
Use dataclasses.asdict() with json.dumps(): from dataclasses import dataclass, asdict; import json; json_str = json.dumps(asdict(obj), indent=2). asdict() recursively converts nested dataclasses to dicts. For lists: json.dumps([asdict(item) for item in items]).
🌐
jsonswitcher.com
jsonswitcher.com › jsonshift › json to python › python to json
Convert Python to JSON — Generate Mock Data & Snippets
🌐
PyPI
pypi.org › project › jsonizable
jsonizable · PyPI
Convert your Python classes into JSON objects easily. ... Jsonizable is a python library that allows to parse json objects into python classes and vice versa.
🌐
Json2CSharp
json2csharp.com › code-converters › json-to-python
JSON to Python Classes Online Converter - Json2CSharp Toolkit
You can always use the online tool above to achieve what we did in this example. Just paste your Json in the left text area, hit that convert button, and you will have your python classes with their mappings created automagically !
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)
🌐
W3Schools
w3schools.com › python › gloss_python_convert_into_JSON.asp
Python Convert From Python to JSON
If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.
🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
Use the separators parameter to change the default separator: json.dumps(x, indent=4, separators=(".
Find elsewhere
🌐
PyPI
pypi.org › project › json-schema-to-class
json-schema-to-class 0.2.4
JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
Json Switcher
jsonswitcher.com › jsonshift › json to python › python to json
Convert Python to JSON — Generate Mock Data & Snippets
May 31, 2026 - Convert Python to JSON online. Easily serialize Python dicts, lists, or objects into clean, structured and valid JSON strings or mock data.
🌐
PYnative
pynative.com › home › python › json › python convert json data into a custom python object
Python Convert JSON data Into a Custom Python Object – PYnative
May 14, 2021 - Now, let’s see the realtime scenario where work with complex Python Objects. And we need to convert custom Python object into JSON. Also, we want to construct a custom Python object from JSON. In this example, we are using two classes Student and Marks.
🌐
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.
🌐
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.
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.

🌐
ExtendsClass
extendsclass.com › json-to-python.html
JSON to Python converter
convert: PHP to PythonPython to javascriptKotlin to javaTypeScript to JavaScriptXPath to CSS selectorJSON to PHPXML to JSON Converter · Playgrounds: MongoDB onlineSQL to MongoDB ConverterSQL onlineOracle onlineSQL Server onlineJavaScript validatorJSONPath TesterXPath TesterRegex TesterSQLite browserMySQL onlinePostgreSQL online
🌐
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 - These kind of Data Classes are implemented/defined as the return value type in FastAPI. FastAPI is able to JSON-encode those class objects and return the JSON formatted response to the caller with no issue.
🌐
w3resource
w3resource.com › python-exercises › python-json-exercise-2.php
Python JSON: Convert Python object to JSON data - w3resource
Write a Python program to convert Python object to JSON data. ... import json # a Python object (dict): python_obj = { "name": "David", "class":"I", "age": 6 } print(type(python_obj)) # convert into JSON: j_data = json.dumps(python_obj) # result is a JSON string: print(j_data)
🌐
Medium
changsin.medium.com › how-to-serialize-a-class-object-to-json-in-python-849697a0cd3
How to Serialize a Class Object to JSON in Python | by Changsin Lee | Medium
August 18, 2022 - · 1. Class Definition · 2. ... 3: Implement JSON Encoder · 4. Handling complex objects ∘ Method 4: Implement to_json() method ∘ Method 5: Implement a custom to_json() method ·...
🌐
Medium
medium.com › @idelossantosruiz › mastering-json-in-python-oop-a-practical-guide-65b39e868c33
Mastering JSON in Python OOP: A Practical Guide | by Ildeberto de los Santos Ruiz | Medium
June 4, 2025 - We’ll cover how to serialize (convert objects to JSON) and deserialize (convert JSON back into objects) using Python’s built-in json module. Along the way, you’ll see practical examples that illustrate best practices for integrating JSON into your classes, managing configuration files, and ensuring data integrity.