简体   繁体   中英

Serialize a custom object inside json object

I am using a third party python library, which returns some data in lists and dictionaries inside them (JSON format). For example, here's a sample entry:

data = [{'a': 1, 'b': 80, 'c': 42, 'd': [{'r': 0, 's': '1', 'u': 5}], 'id': 10, 'k': 60, 'v': 0, 'm': 
{'ty': 'djp', 'nr': '10', 'bc': Adder('179'), 'in': 3}}, {'a': 1, 'b': 70, 'c': 42, 'd': [{'r': 0, 's': 
'1', 'u': 5}], 'y': 10, 'k': 60, 'v': 0, 'm': {'ty': 'djp', 'dx': '10', 'tx': Adder('179'), 'in': 3}}]

My problem is with 'Adder' class which is an object. Everything else are just strings.

So, when I do:

json.dumps(data)

It causes an error message:

Adder('179') is not JSON serializable.

I don't care about serializing this Adder class, so I would somehow like to just make it a string eg "Adder(179)" if possible. Is it possible to make the dumps function work? Class Adder is not my own, maybe I can make it serialized or tell it what to do with it by editing the source or something? Any simple way would be fine.

Just specify a custom encoder class :

class RobustEncoder(json.JSONEncoder):
    def default(self, o):
        try:
            return super(RobustEncoder, self).default(o)
        except TypeError:
            return str(o)    

json.dumps(data, cls=RobustEncoder)

The keyword argument cls is documented in the docs of json.dump .

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