How to put a class inside a JSON

2

Does anyone know how to put a class inside a JSON file? I need to save a class inside a JSON file, however, it returns that this file is not serializable. Does anyone know how I can put this class inside the file, and then use it? Ex:

import json
class Teste:
    pass
dict = {'Class': Teste}
json.dumps(dict)
    
asked by anonymous 06.07.2017 / 15:30

1 answer

3

Jsonpickle:

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.

Pickle

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.

    
06.07.2017 / 17:12