How to place a class within a JSON

Asked

Viewed 205 times

2

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

import json
class Teste:
    pass
dict = {'Class': Teste}
json.dumps(dict)
  • Note: (python 3.6)

  • Have you tried the pickle?

  • What would this be?

  • A Python package. Go to the link and see.

  • Hmm, got it, thanks.

  • To be able to answer, you will have to [Dit] the question and add a [mcve].

  • In this case, if the use of json is mandatory, the jsonpickle.

Show 2 more comments

1 answer

3


Jsonpickle:

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.


Pickle

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.

  • 1

    @Jeffersonquesado, a lapse.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.