How to change json encoding behaviour for serializable python object?

前端 未结 13 1225
无人及你
无人及你 2020-12-02 09:47

It is easy to change the format of an object which is not JSON serializable eg datetime.datetime.

My requirement, for debugging purposes, is to alter the way some cu

13条回答
  •  一整个雨季
    2020-12-02 10:09

    Why can't you just create a new object type to pass to the encoder? Try:

    class MStuff(object):
        def __init__(self, content):
            self.content = content
    
    class mDict(MStuff):
        pass
    
    class mList(MStuff):
        pass
    
    def json_debug_handler(obj):
        print("object received:")
        print(type(obj))
        print("\n\n")
        if  isinstance(obj, datetime.datetime):
            return obj.isoformat()
        elif isinstance(obj,MStuff):
            attrs = {}
            for key in obj.__dict__:
                if not ( key.startswith("_") or key == "content"):
                    attrs[key] = obj.__dict__[key]
    
            return {'orig':obj.content , 'attrs': attrs}
        else:
            return None
    

    You could add validation on the mDict and mList if desired.

提交回复
热议问题