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


I am trying to send a simple dictionary to a json file from python, but I keep getting the "TypeError: 1425 is not JSON serializable" message.

import json
alerts = {"upper":[1425],"lower":[576],"level":[2],"datetime":["2012-08-08 15:30"]}
afile = open("test.json","w")

If I add the default argument, then it writes, but the integer values are written to the json file as strings, which is undesirable.


Answer rating: 292

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

Answer rating: 64

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 TypeError

json.dumps({"value": numpy.int64(42)}, default=convert)

Get Solution for free from DataCamp guru