Reputation: 1053
I wanna create a classmethod that takes a JSON (dictionary) string and creates an instance of the class it's called on.
For example, if I have a class Person
the inherits from a class Jsonable
with age and name:
class Person(Jsonable):
def __init__(self, name, age):
self.name = name
self.age = age
class Jsonable:
@classmethod
def from_json(json_string):
# do the magic here
and if I have a JSON string string = "{'name': "John", 'age': 21}"
and when I say person1 = Person.from_json(string)
I want to create person1 with name John and age 21. I also have to keep the class name in some way so that when I call for example Car.from_json(string)
it raises a TypeError.
Upvotes: 2
Views: 3377
Reputation: 4606
it supposes you have a key __class in you JSON string that holds target class name
import json
class Jsonable(object):
@classmethod
def from_json(cls, json_string):
attributes = json.loads(json_string)
if not isinstance(attributes, dict) or attributes.pop('__class') != cls.__name__:
raise ValueError
return cls(**attributes)
Upvotes: 3