Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

custom object list json serialize in python

Tags:

python

For a custom object I am able to encode into json using JSONEncoder.

class CustomEncoder(JSONEncoder):
    def encode(self, custom):
        prop_dict = {}
        for prop in Custom.all_properties_names():
            if custom.__getattribute__(prop) is not None:
                if prop is 'created_timestamp':
                    prop_dict.update({prop: custom.__getattribute__(
                        prop).isoformat()})
                else:
                    prop_dict.update({prop: custom.__getattribute__(prop)})
        return prop_dict

To generate json, I am using json.dumps(custom, cls=CustomEncoder, indent=True)

Now I have a list of Custom class objects. How do convert the list to json?

custom_list = //get custom object list from service

How do I convert the whole list to json? Do I need to iterate and capture json of each custom object and append to a list with comma separated? I feel like there should be something straightforward I am missing here.

like image 352
suman j Avatar asked Jun 09 '26 10:06

suman j


2 Answers

The custom encoder is called only when needed. If you have a custom thing that the JSON library thinks it can encode, like a string or dictionary, the custom encoder won't be called. The following example shows that encoding an object, or a list including an object, works with a single custom encoder:

import json

class Custom(object):
    pass

class CustomEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, Custom):
            return 'TASTY'
        return CustomEncoder(self, o)

print json.dumps( Custom(), cls=CustomEncoder )
print json.dumps( [1, [2,'three'], Custom()], cls=CustomEncoder )

Output:

"TASTY"
[1, [2, "three"], "TASTY"]
like image 186
johntellsall Avatar answered Jun 11 '26 22:06

johntellsall


In my way, I convert object to dict then using json.dumps list of dict:

def custom_to_dict(custom):
    return {
        'att1': custom.att1,
        'att2': custom.att2,
        ...
    }

#custom_list is your list of customs
out = json.dumps([custom_to_dict(custom) for custom in custom_list])

It might be helpful

like image 41
heroandtn3 Avatar answered Jun 11 '26 22:06

heroandtn3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!