rect_list = list()
...
rect_list.append(rect1)
rect_list.append(rect2)
...
rsp = {'rect-list': rect_list}
return json.dumps(rsp)
报错
File "C:\Users\mo\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\mo\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type int32 is not JSON serializable
原因
字典格式化为JSON不支持numpy.int32。np.float32、np.array等存在类似问题。
解决(两种 方法原理相同)
- 转Json前,将np类型强制转换为python类型
def cv_rect_to_dict(cv_rect):
x, y, w, h = cv_rect
return {'x': int(x), 'y': int(y), 'w': int(w), 'h': int(h)}
- 继承实现自定义Json Encoder
class ZJsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, numpy.integer):
return int(obj)
elif isinstance(obj, numpy.floating):
return float(obj)
elif isinstance(obj, numpy.ndarray):
return obj.tolist()
else:
return super(ZJsonEncoder, self).default(obj)
用法:
rsp = {'rect-list': rect_list}
return json.dumps(rsp, cls=ZJsonEncoder)