0

How to convert JSON data into a Python class?

class AnotherClass():
    test: int

class MyClass():
    a: int
    c: AnotherClass


json = {
    "a": 1,
    "c": {
        "test": 2
    }
}

my_class = MyClass(json)
print(my_class.a) # 1
print(my_class.c.test) # error

I've tried using the _dict_ attribute, but the variable in the member class is not assigned a value.

Is there a way to parse the json and input data up to the variable of the member class without manually assigning values?

class MyClass():
    a: int
    c: AnotherClass

    def __init__(self, json) -> None:
        self.__dict__ = json

my_class = MyClass(json)
print(my_class.a) # 1
print(my_class.c.test) # AttributeError: 'dict' object has no attribute 'test'
Yammo
  • 5
  • 1
  • https://stackoverflow.com/q/6578986/3990714 – nonamorando Nov 11 '22 at 07:25
  • 2
    In order for `c` to hold an instance of `AnotherClass`, you'd need to inspect the type annotation of `MyClass` and instantiate the annotated `AnotherClass` found there, passing it the values of the `"c"` key. And you'd probably need to do that recursively for all classes to cover more deeply nested classes. A simple assignment to `__dict__` won't do any of that. – deceze Nov 11 '22 at 07:26
  • Does this answer your question? [How to convert JSON data into a Python object?](https://stackoverflow.com/questions/6578986/how-to-convert-json-data-into-a-python-object) – Robert Nov 11 '22 at 17:31

1 Answers1

0

You can use dataclasses as follows, note the quirk of __post_init__ to handle nested dataclasses:

from dataclasses import dataclass

@dataclass
class AnotherClass:
    test: int

@dataclass
class MyClass:
    a: int
    c: AnotherClass

    def __post_init__(self):
        self.c = AnotherClass(**self.c)

json = {
    "a": 1,
    "c": {
        "test": 2
    }
}

my_class = MyClass(**json)
print(my_class.a)  # 1
print(my_class.c.test)  # 2
TomerG
  • 181
  • 3