I am trying to save one dict data in .json file format. When I try json.dump(JSON, json_file), it throws the error: Object of type int32 is not JSON serializable.
I know, it is because I am using some numpy data in dictionary.
Here is the code, that I tried.
import json
for i in range(1):
g = Balea_coordinate[i] # numpy array
h = DM_coordinate[i] # numpy array
JSON = {"img_metadata" : {
"date" : "date",
"Method" : "SIFT+RANSACK",
"filename" : "Balea_",
"size" : "SIZE",
"regions":[{"0":{"shape_attributes":{"name":"polygon","all_points_x":[g[0,0,0],g[1,0,0],g[2,0,0],g[3,0,0]],
"all_points_y":[g[0,0,1],g[1,0,1],g[2,0,1],g[3,0,1]]},
"region_attributes":{"name":"Logo","type":"Balea"}},
"1":{"shape_attributes":{"name":"polygon","all_points_x":[h[0,0,0],h[1,0,0],h[2,0,0],h[3,0,0]],
"all_points_y":[h[0,0,1],h[1,0,1],h[2,0,1],h[3,0,1]]},
"region_attributes":{"name":"Logo","type":"DM"}}}]}}
with open('personal.json', 'w') as json_file:
json.dump(JSON, json_file)
´´´
I suggest extending the default JSONEncoder to handle the numpy.int32 type (or any other required type).
class npEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.int32):
return int(obj)
return json.JSONEncoder.default(self, obj)
Then use it in json.dump(JSON, json_file, cls=npEncoder)
. Depending on your requirements, a simple conversion np.int32 -> int
might not be sufficient.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.