Assume I have several classes:
class Assignee:
gid: str
name: str
class Task:
gid: str
name: str
created_at: datetime
assignee: Assignee
and I receive a JSON, that I want to translate into my Task class instance:
{
"gid": "#1",
"name": "my task",
"created_at": "2022-11-02T10:25:49.806Z",
"assignee": {
"gid": "#a1",
"name": "assignee name"
}
}
I need to get the strong typed result, not a dict. Is it possible to convert from JSON string to a class instance automatically?
In C# we can do it with JsonConvert.DeserializeObject<Task>(json_string).
In Python I found a jsonpickle library, but as far as I see, it cannot do it automatically. Am I missing anything?
In real life I have many more classes and JSON properties.
Assignee.__dict__['__dataclass_fields__'].keys(). From there, you can probe what JSON.loads()gave you, and populate a newly created object. If you put the values into dictd, thenAssignee(**d)produces what you want. Once you've put together an implementation you're happy with, please share it with us here.