"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python? "TypeError: (Integer) is not JSON serializable" when serializing JSON in Python? python python

"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python?


I found my problem. The issue was that my integers were actually type numpy.int64.


It seems like there may be a issue to dump numpy.int64 into json string in Python 3 and the python team already have a conversation about it. More details can be found here.

There is a workaround provided by Serhiy Storchaka. It works very well so I paste it here:

def convert(o):    if isinstance(o, numpy.int64): return int(o)      raise TypeErrorjson.dumps({'value': numpy.int64(42)}, default=convert)


as @JAC pointed out in the comments of the highest rated answer, the generic solution (for all numpy types) can be found in the thread Converting numpy dtypes to native python types.

Nevertheless, I´ll add my version of the solution below, as my in my case I needed a generic solution that combines these answers and with the answers of the other thread. This should work with almost all numpy types.

def convert(o):    if isinstance(o, np.generic): return o.item()      raise TypeErrorjson.dumps({'value': numpy.int64(42)}, default=convert)