1

I have created a dict that contains a string key and some class as a value. Now I want to use json to serialize it and de-serialize it.

class A:
    def __init__(self, val):
        self.val = val


class B(A):
    def __init__(self, val, additional_val):
        super(B, self).__init__(val)
        self.additional_val= additional_val


class C(B):
    def __init__(self, val, additional_val, enabled):
        super(C, self).__init__(val, additional_val)
        self.enabled = enabled


my_dict = {'0': A(0), '1': B(5, 6), '2': C(7,8,True)}

now I want to serialize it. I found that the easiest way to serialize it with jsons (using python 3.6). But how can I de-serialize it back to the original objects ? all the examples that I found was for very simple objects (str, dict, list).

yehudahs
  • 2,488
  • 8
  • 34
  • 54
  • Please provide a [MCVE](https://stackoverflow.com/help/minimal-reproducible-example). Where is the serializing code? What did you try so far? – Tim Dec 04 '19 at 07:05
  • Could this answer work for you? https://stackoverflow.com/questions/3768895/how-to-make-a-class-json-serializable – mccandar Dec 04 '19 at 07:21

1 Answers1

-1

Try this:

import json
def convert_to_dict(obj):
"""
A function takes in a custom object and returns a dictionary representation of the object.
This dict representation includes meta data such as the object's module and class names.
"""

    #  Populate the dictionary with object meta data
    obj_dict = {
    "__class__": obj.__class__.__name__,
    "__module__": obj.__module__
}

    #  Populate the dictionary with object properties
    obj_dict.update(obj.__dict__)

    return obj_dict

my_dict = {'0': A(0), '1': B(5, 6), '2': C(7,8,True)}
mydict_dump = json.dumps(my_dict, default=convert_to_dict, indent=4, sort_keys=True)
final_result = json.loads(mydict_dump)

print(final_result)

You can refer to this medium article to learn more:

JSON — The Python Way

mrasoolmirza
  • 787
  • 1
  • 6
  • 22
  • in order for this answer to work you need to add to the json.load(mydict_dump, object_hook=dict_to_obj) as mentioned in the link in the answer. – yehudahs Dec 04 '19 at 09:46