【发布时间】: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