“TypeError: (Integer) is not JSON serializable” wh

2019-01-31 04:40发布

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')
afile.write(json.dumps(alerts,encoding='UTF-8'))
afile.close()

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

afile.write(json.dumps(alerts,encoding='UTF-8',default=str))

4条回答
家丑人穷心不美
2楼-- · 2019-01-31 05:17

You have Numpy Data Type, Just change to normal int() or float() data type. it will work fine.

查看更多
Explosion°爆炸
3楼-- · 2019-01-31 05:25

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 default(o):
    if isinstance(o, numpy.int64): return int(o)  
    raise TypeError

json.dumps({'value': numpy.int64(42)}, default=default)
查看更多
不美不萌又怎样
4楼-- · 2019-01-31 05:27

Alternatively you can convert your object into a dataframe first:

df = pd.DataFrame(obj)

and then save this dataframe in a json file:

df.to_json(path_or_buf='df.json')

Hope this helps

查看更多
来,给爷笑一个
5楼-- · 2019-01-31 05:42

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

查看更多
登录 后发表回答