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.
3
Answers
Not quite what you are asking, but the
json
module already produces suitable dicts. All you need to do is define how to instantiate your classes given adict
.Part of this requires you to assume what type each key’s value must be instantiated as.
Assuming the json properties match the property names exactly in the classes, you can use kwargs in the constructors to put the object together.
Use pydantic. It has type validation (and other cool features) and is very easy to use: