Why does json.dumps(list(np.arange(5))) fail while json.dumps(np.arange(5).tolist()) works

前端 未结 3 1675
鱼传尺愫
鱼传尺愫 2020-12-09 03:15

I noticed this problem when a computer running Ubuntu was updated recently and the default version of Python changed to 2.7.

import json
import numpy as np

         


        
3条回答
  •  醉话见心
    2020-12-09 04:03

    Because the elements of a NumPy array are not native ints, but of NUmPy's own types:

    >>> type(np.arange(5)[0])
    
    

    You can use a custom JSONEncoder to support the ndarray type returned by arange:

    import numpy as np
    import json
    
    class NumPyArangeEncoder(json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj, np.ndarray):
                return obj.tolist() # or map(int, obj)
            return json.JSONEncoder.default(self, obj)
    
    print(json.dumps(np.arange(5), cls=NumPyArangeEncoder))
    

提交回复
热议问题