序列化自定义对象列表

时间:2015-03-06 10:24:26

标签: python django python-2.7

我正在从数据库创建自定义对象列表。自定义对象类和列表创建如下所示。如何序列化保存此自定义数据的列表?

class MyCustomObject():
    """For displaying the records"""
    def __init__(self):
        self.rec_id = ""
        self.place = ""

rec_list = [] #The List
# Creating a list of MyCustomObject's from rows
for col in rows:
    rec = MyCustomObject()            
    rec.rec_id = col[0]
    rec.place = col[1]
    rec_list.append(recently_viewed)

如何将此MyCustomObject列表序列化为JSON。

2 个答案:

答案 0 :(得分:0)

您可以尝试编写自己的序列化程序,如下所示:

import json

class MyCustomObject():
    """For displaying the records"""
    def __init__(self):
        self.rec_id = ""
        self.place = ""

class mySerializer(json.JSONEncoder):
    def default(self, obj):
        return obj.__dict__

rec_list = [] #The List
# Creating a list of MyCustomObject's from rows
rows = [[1,2],[3,4]]
for col in rows:
    rec = MyCustomObject()            
    rec.rec_id = col[0]
    rec.place = col[1]
    rec_list.append(rec)

print [json.dumps(r, cls=mySerializer)  for r in rec_list]

输出:

 ['{"place": 2, "rec_id": 1}', '{"place": 4, "rec_id": 3}']

答案 1 :(得分:0)

通过扩展JsonEncoder(https://docs.python.org/2/library/json.html#json.JSONEncoder

所以你会得到类似的东西;

import json

class MyJsonEncoder
    def default(self, obj):
        if isinstance(obj, MyCustomObject):
            return {}  # dict representation of your object
        return super(MyJsonEncoder, self).dumps(obj)

json.dumps(rec_list, encoder=MyJsonEncoder)