在嵌套字典中序列化对象的最简单方法

Jiy*_*ssa 6 python json

我想序列化以下字典中具有键“manager_objects”的所有对象。最简单的方法是什么?

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: {}
            }

        }
    }

}
Run Code Online (Sandbox Code Playgroud)

}

小智 5

您可以编写自己的 JsonEncoder (或使用 @PaulDapolito 描述的方法)。但是,只有当您知道带有 key 的项目的类型时,这两种方法才有效manager_object。来自文档:要使用自定义 JSONEncoder 子类(例如,重写 default() 方法以序列化其他类型的子类),请使用 cls kwarg 指定它;否则使用 JSONEncoder。

# 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)
Run Code Online (Sandbox Code Playgroud)


Pau*_*ito 3

如果你的字典包含 Python/json默认情况下不知道如何序列化的对象,你需要给出json.dumpjson.dumps一个函数作为其default关键字,告诉它如何序列化这些对象。举例来说:

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)
Run Code Online (Sandbox Code Playgroud)