Creating the class:
import jsonpickle
class Foo():
def test(self):
return 'bar'
foo = Foo()
Converting the object into a JSON string:
jfoo = jsonpickle.encode(foo)
Rebuilding the python object from the JSON string:
foo2 = jsonpickle.decode(jfoo)
Executing the recreated object (the class):
foo2.test()
'bar'
Click here for the documentation.
If you are not required to use json, we have the (more secure) pickle option in python:
Creating the class:
import pickle
class Foo():
def test(self):
return 'bar'
Serializing:
foo = Foo()
with open('foo.pickle', 'wb') as f:
pickle.dump(foo, f, pickle.HIGHEST_PROTOCOL)
Reading from disk to memory (Deserializing):
with open('foo.pickle', 'rb') as f:
foo2 = pickle.load(f)
Running the deserialized class:
foo2.test()
'bar'
Click here for documentation.