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 - Explanation: json.dumps(p1.__dict__) line converts the object's __dict__ attribute, which holds the instance's attributes as a dictionary, into a JSON string. Defining a to_dict() method within the class gives you more control over how the object is serialized.
Top answer
1 of 16
735

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
206

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)
Discussions

How do I convert a json file to a python class? - Stack Overflow
If you want to dynamically change ... use a class. ... Since it sounds like your data might be expected to be dynamic and you want the freedom to add more fields in the JSON object without reflecting the same changes in the model, I'd also suggest to check out typing.TypedDict instead a dataclass. Here's an example with TypedDict, which should work in Python 3.7+. Since ... More on stackoverflow.com
🌐 stackoverflow.com
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
How should/can I convert loaded JSON data into Python objects?
I have JSON input like this: { ... how serde from Rust works. I would like to define a class like this: @dataclass class MyClass: accountID: str accountClass: str id: str openTime: str priceDifference: float After loading the JSON data what is the best ...... More on discuss.python.org
🌐 discuss.python.org
0
1
October 25, 2022
how to convert json to python class? - Stack Overflow
I want to Json to Python class. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Json2CSharp
json2csharp.com › code-converters › json-to-python
JSON to Python Classes Online Converter - Json2CSharp Toolkit
Convert any JSON string to Python classes online. - Json2CSharp.com is a free parser and converter that will help you generate Python classes from a JSON object.
Top answer
1 of 3
11

Since it sounds like your data might be expected to be dynamic and you want the freedom to add more fields in the JSON object without reflecting the same changes in the model, I'd also suggest to check out typing.TypedDict instead a dataclass.

Here's an example with TypedDict, which should work in Python 3.7+. Since TypedDict was introduced in 3.8, I've instead imported it from typing_extensions so it's compatible with 3.7 code.

from __future__ import annotations

import json
from io import StringIO
from typing_extensions import TypedDict


class Account(TypedDict):
    email: str
    password: str
    name: str
    salary: int


json_data = StringIO("""{
    "acc1":{
        "email":"[email protected]",
        "password":"acc1",
        "name":"ACC1",
        "salary":1
    },
    "acc2":{
        "email":"[email protected]",
        "password":"acc2",
        "name":"ACC2",
        "salary":2,
        "someRandomKey": "string"
    }
}
""")

data = json.load(json_data)
name_to_account: dict[str, Account] = data

acct = name_to_account['acc2']

# Your IDE should be able to offer auto-complete suggestions within the
# brackets, when you start typing or press 'Ctrl + Space' for example.
print(acct['someRandomKey'])

If you are set on using dataclasses to model your data, I'd suggest checking out a JSON serialization library like the dataclass-wizard (disclaimer: I am the creator) which should handle extraneous fields in the JSON data as mentioned, as well as a nested dataclass model if you find your data becoming more complex.

It also has a handy tool that you can use to generate a dataclass schema from JSON data, which can be useful for instance if you want to update your model class whenever you add new fields in the JSON file as mentioned.

2 of 3
7

This way you lose some dataclass features.

  • Such as determining whether it is optional or not
  • Such as auto-completion feature

However, you are more familiar with your project and decide accordingly

There must be many methods, but this is one of them:

@dataclass
class Account(object):
    email: str
    password: str
    name: str
    salary: int

    @classmethod
    def from_json(cls, json_key):
        file = json.load(open("1.txt"))
        keys = [f.name for f in fields(cls)]
        # or: keys = cls.__dataclass_fields__.keys()
        json_data = file[json_key]
        normal_json_data = {key: json_data[key] for key in json_data if key in keys}
        anormal_json_data = {key: json_data[key] for key in json_data if key not in keys}
        tmp = cls(**normal_json_data)
        for anormal_key in anormal_json_data:
            setattr(tmp,anormal_key,anormal_json_data[anormal_key])
        return tmp

test = Account.from_json("acc1")
print(test.age)
Top answer
1 of 16
321

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.

🌐
Python
docs.python.org › 3 › library › json.html
JSON encoder and decoder — Python 3.14.3 documentation
1 month ago - 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)¶
🌐
Python.org
discuss.python.org › python help
How should/can I convert loaded JSON data into Python objects? - Python Help - Discussions on Python.org
October 25, 2022 - I have JSON input like this: { "accountID": "001-002-003-004", "accountClass": "Primary", "id": "1-2", "openTime": "2019-12-21T02:12:17.122Z", "priceDifference": "0.12345", } I would like to deserialise it in…
Find elsewhere
🌐
Code Beautify
codebeautify.org › json-to-python-pojo-generator
JSON to Python Generator to create Python Pojo
This tool will help you to convert your JSON String/Data to Python Class Object.
🌐
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 - Learn how to write a custom JSON Decoder to convert JSON into a custom Python object. Learn Use of jsonpickle to convert JSON into a custom Python Object
🌐
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.
🌐
PYnative
pynative.com › home › python › json › make a python class json serializable
Make a Python Class JSON Serializable
May 14, 2021 - Python json module has a JSONEncoder class. You can extend it If you want more customized output. i.e., you will have to subclass JSONEncoder so you can implement your custom JSON serialization.
🌐
Python.org
discuss.python.org › python help
Convert several layers deep nested JSON to instance of a class with nested class attributes - Python Help - Discussions on Python.org
March 5, 2024 - Hello, I’m trying to write tests using pytest library. I have a JSON file that I want to have as an input so I made a pytest.fixture to return the data converted to PlanRequest class instance, because that’s what I need to work with in my test function. @pytest.fixture def test_data(): file = os.path.join(os.path.dirname(__file__), 'test_data.json') with open(file) as json_file: json_data = json.load(json_file) job = PlanRequest(json_data) _preprocess_job(job) ...
🌐
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....
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-json-data-into-a-custom-python-object
Convert JSON data Into a Custom Python Object - GeeksforGeeks
July 3, 2025 - We can easily convert JSON data into a custom object by using the json.loads() or json.load() methods. The key is the object_hook parameter, which allows us to define how the JSON data should be converted into a custom Python object.
🌐
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
🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
Python has a built-in package called json, which can be used to work with JSON data.
🌐
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

Top answer
1 of 1
3

Using the ** operator is probably the preferred way to do it, as long as your constructor parameters match the names of your JSON attributes exactly (like they do in your example) and as long as there's not additional parameters on the constructor that could wreak havoc:

def Message:
    def __init__(greeting: str, wipe_c_drive: bool = False):
        self.greeting = greeting
        if wipe_c_drive:
            shutil.rmtree('C:/')


workfile = json.load(open('greetings.json', 'r'))
hello = Message(**workfile['hello'])

And the data in greetings.json:

{
  "hello": {
    "greeting": "Hello there!"
  }
}

What could possibly go wrong, right?

The ** operator is a 'spreading' operator, it take a key/value pair data object like a dictionary, and spreads it - typically to provide keyword arguments for a function:

def say(greeting, name):
    print(f'{greeting} to you, {name}!')


d = {'greeting': 'hello', 'name': 'AnFa')
say(**d)

This works in your case as well, since a JSON object is loaded as a dictionary and thus can be spread using the ** operator. And since the attributes of your JSON object exactly match the names of your keyword parameters for the constructor, it works.

Similarly, the * operators spreads a list:

xs = ['hello', 'AnFa']
say(*xs)

This has the same result, but tries to pass the values as positional parameters.

Knowing the above, you may also understand why you sometimes see this:

def some_func(x, *args, **kwargs):
    print(x)
    some_other_func(*args, **kwargs)

Here, the *args and **kwargs work to capture positional and keyword parameters in args (arguments) and kwargs (keyword arguments) and the second time, they spread them back into the call to some_other_func. Those names args and kwargs are not magical, they're just conventions.

If you want something a bit less risky (because of the reasons explained above), you could give your class 'to_json' and 'from_json' methods, but fairly soon things will get complicated and you may want to look into existing libraries instead, as user @LeiYang suggests (and there are many of those).