3

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.

suman j
  • 6,710
  • 11
  • 58
  • 109
  • 1
    How is this duplicate? I am asking for `list` object json conversion. As you see in the code, I already have `JSONEncoder` used which is the suggested in many posts. But still it does not convert the list to json for me. – suman j May 31 '14 at 13:58

2 Answers2

5

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"]
johntellsall
  • 14,394
  • 4
  • 46
  • 40
  • 1
    1. CustomEncoder knows how to encode a `single` custom object. So did not work when I pass list. 2. Created another encoder `ListCustomEncoder` which iterates over list elements and calls encode on each of them and appends the encoded json to a list. This also did not work. – suman j Jun 02 '14 at 12:52
  • @jack, thanks for the feedback. I've rewritten the sample code and provided an example -- I hope it clarifies things for you. – johntellsall Jun 02 '14 at 16:59
  • Thanks. my encoder defined "encode" instead of "default" method. It worked perfect now. – suman j Jun 04 '14 at 13:11
1

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

heroandtn3
  • 164
  • 1
  • 7
  • Thanks. my code (in response) is same as this. converting to dict is done by encoder. and these dict objects are collected in a list and dumped using `json.dumps` – suman j Jun 02 '14 at 17:49
  • @Jack: no, your code creates list of strings instead list of dicts – heroandtn3 Jun 02 '14 at 17:51
  • 1
    Thanks for the explanation @heroandtn3. It worked fine now after I changed my encoder. – suman j Jun 04 '14 at 13:13