Python中json.dumps序列化int32类型列表报错的解决咨询
解决JSON序列化int32类型的问题
你遇到的问题根源是temp_list_area_lips里的元素是numpy int32类型,而非Python原生的int类型,JSON默认序列化器无法识别这种自定义数值类型。手动赋值的列表用的是原生int,所以能正常运行。下面是几种可行的解决方法:
方法一:批量转换为原生int
遍历嵌套列表,把每个int32元素转成Python原生int:list_area_lips = [[int(num) for num in sublist] for sublist in temp_list_area_lips]处理后再执行
json.dumps就能正常序列化。方法二:利用numpy的tolist()方法
如果temp_list_area_lips本身是numpy数组,或者由numpy元素构成的嵌套结构,直接调用tolist()方法可以自动将所有numpy数值类型转换为Python原生类型:list_area_lips = temp_list_area_lips.tolist()这个方法对嵌套列表、多维数组都适用,代码更简洁。
方法三:自定义JSON编码器
写一个自定义编码器,让JSON序列化器能识别numpy int32类型:import json import numpy as np class NumpyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.int32): return int(obj) # 可扩展处理其他numpy类型,比如int64、float32等 # elif isinstance(obj, np.int64): # return int(obj) return super().default(obj)调用时指定编码器:
return json.dumps( {"faceDetected": face_detected, "listFaceUrl": list_face_url, "listFaceCategory": list_face_category, "listAreaLips": list_area_lips}, cls=NumpyEncoder )这种方法适合需要频繁处理numpy类型序列化的场景,不用每次手动转换列表。
内容的提问来源于stack exchange,提问作者KEZIA ANGELINE
相关产品推荐
相关产品推荐

