Easiest way to serialize an object in a nested dictionary

I would like to serialize all objects having key "manager_objects" in the following dictionary. What's the easiest way to do this?

department {
id: 1,
name: 'ARC',
manager_object: <Object>
sub_department: {
    id: 5,
    name: 'ABC'
    manager_object: <Object>
    sub_department: {
        id: 7,
        name: 'TRW',
        manager_object: <Object>
        sub_department: {
            id: 9,
            name: 'MYT',
            manager_object: <Object>
            sub_deparment: {
                id: 12,
                name: 'NMY'
                manager_object: <Object>
                sub_department: {}
            }

        }
    }

}

      

}

+3


source to share


2 answers


If your dictionary contains objects that Python / json

doesn't know how to serialize by default, you need to provide json.dump

or a json.dumps

function as a keyword default

that tells it how to serialize those objects, Example:



import json

class Friend(object):
    def __init__(self, name, phone_num):
        self.name = name
        self.phone_num = phone_num

def serialize_friend(obj):
   if isinstance(obj, Friend):
       serial = obj.name + "-" + str(obj.phone_num)
       return serial
   else:
       raise TypeError ("Type not serializable")

paul = Friend("Paul", 1234567890)
john = Friend("John", 1234567890)

friends_dict = {"paul": paul, "john": john}
print json.dumps(friends_dict, default=serialize_friend)

      

+2


source


You can write your own JsonEncoder (or use the method described by @PaulDapolito). But both methods only work if you know the type of the keyed item manager_object

. From the docs: to use a custom JSONEncoder subclass (for example, which overrides the default () method to serialize additional types), specify it with cls kwarg; otherwise, JSONEncoder is used.



# Example of custom encoder
class CustomJsonEncoder(json.JSONEncoder):
    def default(self, o):
        # Here you can serialize your object depending of its type
        # or you can define a method in your class which serializes the object           
        if isinstance(o, (Employee, Autocar)):
            return o.__dict__  # Or another method to serialize it
        else:
            return json.JSONEncoder.encode(self, o)

# Usage
json.dumps(items, cls=CustomJsonEncoder)

      

+3


source







All Articles