【问题标题】:python (built-in)json de/serilazation with nested custom types带有嵌套自定义类型的python(内置)json de/serization
【发布时间】:2013-12-11 14:06:32
【问题描述】:

我对 python2 (2.7) 中的 json 模块没有太多经验。现在我面临一个问题:如何将自定义对象序列化为 json,然后再将其反序列化。

我以这个对象层次结构为例:

class Company(object):
    def __init__(self, company_id):
        self.company_id = company_id
        self.name = ''
        # other 10 attributes with simple type
        ...
        self.departments = [] #list of Dept objects

class Dept(object):
    def __init__(self, dept_id):
        self.dept_id = dept_id
        self.name = ''
        # other 10 attributes with simple type
        ...
        self.persons = [] #list of Person objs


class Person(object):
    def __init__(self, per_id):
        self.per_id = per_id
        self.name = ''
        # other 10 attributes with simple type
        ...
        self.skills = [] #list of Skill objs

class Skill(object):
    def __init__(self, skill_id):
        self.skill_id = skill_id
        self.name = ''
        # other 10 attributes with simple type
        ...
        self.foos = [] #list of Foo objs

class Foo(object):
    .....

现在假设我从Company 获得了一个对象,其中包含来自嵌套对象的所有属性和列表。我想将对象保存到 json 文件中。稍后将其加载回来,以便同时加载那些嵌套对象 (departments, persons, skills)。

我读过 pydoc,知道 json de/encoding 是基于 dict 的。我现在可以用这个进行序列化:

    json.dump(company_obj, jsonfile, default = lambda o: o.__dict__, sort_keys=True, indent=4)

但以后很难将其恢复到Company

我认为这个问题很常见。我在 SO 和 google 上搜索过,没有找到有用的信息。

在这种情况下,进行 json 序列化和反序列化的正确方法是什么。

【问题讨论】:

    标签: python json python-2.7 serialization


    【解决方案1】:

    您需要的是自定义编码器和解码器。这些记录在这里:http://docs.python.org/2/library/json.html#encoders-and-decoders

    一个可行的解决方案是在编码时将限定的类名添加到字典中,并在解码时使用它来创建正确类的实例。

    【讨论】:

    • 我想我明白你的意思了。我创建了两个函数,一个将__class____module__ 添加到dict 进行编码。另一个,首先执行__import__,然后检查__class__ 的类型并实例化具有相应属性的正确对象。我将这两个函数用作default=(编码)和object_hook=(解码)。到目前为止它有效......我认为用py处理json会更容易。我希望我做对了。
    猜你喜欢
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多