How to change json encoding behaviour for serializable python object?

前端 未结 13 1223
无人及你
无人及你 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:18

    Try the below. It produces the output you want and looks relatively simple. The only real difference from your encoder class is that we should override both decode and encode methods (since the latter is still called for types the encoder knows how to handle).

    import json
    import datetime
    
    class JSONDebugEncoder(json.JSONEncoder):
        # transform objects known to JSONEncoder here
        def encode(self, o, *args, **kw):
            for_json = o
            if isinstance(o, mDict):
                for_json = { 'orig' : o, 'attrs' : vars(o) }
            elif isinstance(o, mList):
                for_json = { 'orig' : o, 'attrs' : vars(o) }
            return super(JSONDebugEncoder, self).encode(for_json, *args, **kw)
    
        # handle objects not known to JSONEncoder here
        def default(self, o, *args, **kw):
            if isinstance(o, datetime.datetime):
                return o.isoformat()
            else:
                return super(JSONDebugEncoder, self).default(o, *args, **kw)
    
    
    class mDict(dict):
        pass
    
    class mList(list):
        pass
    
    def test_debug_json():
        games = mList(['mario','contra','tetris'])
        games.src = 'console'
        scores = mDict({'dp':10,'pk':45})
        scores.processed = "unprocessed"
        test_json = { 'games' : games , 'scores' : scores , 'date': datetime.datetime.now() }
        print(json.dumps(test_json,cls=JSONDebugEncoder))
    
    if __name__ == '__main__':
        test_debug_json()
    

提交回复
热议问题