So I got a problem that I don't know how to solve.
I want to load objects from JSON files and convert them into a specific object in python. For example, I got some JSON like this:
{
"Class1":{
"name":"str",
"value":float,
"description":"str",
etc.
},
"Class2":{
"name":"str",
"value":float,
"description":"str"
}
}
And some Python code like this:
class Class1:
name:str
value:float
description:str
class Class2(Class1):
def someMethod(self):
pass
How can I turn this in the easiest way possible in the class it belongs to?
I already found some solutions online but they would require a custom encoder for each class. But I want something like one function which creates all objects.
CodePudding user response:
dataclass should do the job . The constructor of a dataclass can handle data easily.
from dataclasses import dataclass
@dataclass
class Class1:
name:str
value:float
description:str
@dataclass
class Class2(Class1):
def someMethod(self):
pass
data ={
"Class1":{
"name":"str",
"value":1.0,
"description":"str",
},
"Class2":{
"name":"str",
"value":2.0,
"description":"str"
}
}
for k, vals in data.items():
print(locals()[k](**vals))
# Class1(name='str', value=1.0, description='str')
# Class2(name='str', value=2.0, description='str')
CodePudding user response:
You can use dataclasses
as mentioned already by Glauco. If you intend to generate them from the json, in the style you mentioned, below is an example appraoch.
from dataclasses import make_dataclass
from pydoc import locate
definitions = {
"Class1": {
"name": "str",
"value": "float",
"description": "str",
},
"Class2": {
"name": "str",
"value": "float",
"description": "str"
}
}
def make_class(name, definition):
def_fields = [(name, locate(typ)) for name, typ in definition.items()]
return make_dataclass(name, def_fields)
classes = [make_class(name, definition) for name, definition in definitions.items()]
CodePudding user response:
Use dataclass
from dataclasses import dataclass
data = {
"clazz_1":{
"name":"jack",
"value":12.5,
"description":"desc1",
},
"clazz_2":{
"name":"jim",
"value":45.77,
"description":"desc2"
}
}
@dataclass
class A:
name:str
value: float
description: str
@dataclass
class B:
name:str
value: float
description: str
@dataclass
class Parent:
clazz_1: A
clazz_2: B
p: Parent = Parent(**data)
print(p)
output
Parent(clazz_1={'name': 'jack', 'value': 12.5, 'description': 'desc1'}, clazz_2={'name': 'jim', 'value': 45.77, 'description': 'desc2'})