Creating the class:
import jsonpickle
class Foo():
def test(self):
return 'bar'
foo = Foo()
Converting the obejto into a JSON string:
jfoo = jsonpickle.encode(foo)
Recreating the python object from the JSON string:
foo2 = jsonpickle.decode(jfoo)
Executing the recreated object (class):
foo2.test()
'bar'
Click here for documentation.
If you are not required to use json, we have the pickle option (more secure) 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)
Executing the deserialized class:
foo2.test()
'bar'
Click here for documentation.
Note: (python 3.6)
– DoutorWhite
Have you tried the
pickle
?– Woss
What would this be?
– DoutorWhite
A Python package. Go to the link and see.
– Woss
Hmm, got it, thanks.
– DoutorWhite
To be able to answer, you will have to [Dit] the question and add a [mcve].
– Woss
In this case, if the use of json is mandatory, the jsonpickle.
– Sidon