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

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

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, 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)) 
+136
json python encoding typeerror
Aug 13 '12 at 21:10
source share
6 answers

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

+240
Aug 13 2018-12-12T00:
source share

It looks like there might be a problem unloading numpy.int64 into a json string in Python 3, and the python development team has already talked about this. More information can be found here .

A workaround was provided by Sergey Storchak. This works very well, so I insert this here:

 def convert(o): if isinstance(o, numpy.int64): return int(o) raise TypeError json.dumps({'value': numpy.int64(42)}, default=convert) 
+29
May 29 '18 at 6:32
source share

This solved the problem for me:

 def serialize(self): return { my_int: int(self.my_int), my_float: float(self.my_float) } 
+3
Apr 07 '19 at 20:43 on
source share

Just convert numbers from int64 (from numpy) to int .

For example, if the variable x is int64:

 int(x) 

If it is an int64 array:

 map(int, x) 
+2
Jun 04 '19 at 17:11
source share

Alternatively, you can first convert your object to a data array:

 df = pd.DataFrame(obj) 

and then save this dataframe to json file:

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

Hope this helps

+1
Oct 30 '18 at 12:46
source share

You have a Numpy Data Type, just change to a regular int () or float () data type. this will work fine.

0
Aug 28 '18 at 15:50
source share



All Articles