2

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.

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

3 Comments

However, say I have the following method in the Jsonable: def to_json(self, indent=4): return json.dumps(self.__dict__, indent) which returns a dictionary with attributes as keys and values as dict values. And I want to use this same string as a parameter in the from_json method, which wouldn't have a __class key.
I'm afraid it will not contain anything like class name, so you will need to put it there by yourself.
Yeah I think I figured it out. I made it work anyways! :) Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.