简体   繁体   中英

Serialize a list of custom objects

I am creating an list of custom objects from a database. The custom object class and the list creation is shown below. How can I serialize the list holding this custom data?

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)

How can I serialize this list of MyCustomObject s to JSON.

you could try writing your own serializer as below:

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]

output:

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

By extending JsonEncoder ( https://docs.python.org/2/library/json.html#json.JSONEncoder )

So you will get something like;

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM