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.

1
  • 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. Commented May 31, 2014 at 13:58

2 Answers 2

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"]
Sign up to request clarification or add additional context in comments.

3 Comments

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.
@jack, thanks for the feedback. I've rewritten the sample code and provided an example -- I hope it clarifies things for you.
Thanks. my encoder defined "encode" instead of "default" method. It worked perfect now.
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

3 Comments

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
@Jack: no, your code creates list of strings instead list of dicts
Thanks for the explanation @heroandtn3. It worked fine now after I changed my encoder.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.