問(wèn)題描述
在導(dǎo)入Python json包,調(diào)用json.dump/dumps函數(shù)時(shí),可能會(huì)遇到TypeError: Object of type xxx is not JSON serializable錯(cuò)誤,也就是無(wú)法序列化某些對(duì)象格式。
解決辦法
自定義序列化方法
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, time):
return obj.__str__()
else:
return super(NpEncoder, self).default(obj)
然后在調(diào)用json.dump/dumps時(shí),指定使用自定義序列化方法
json.dumps(data, cls=MyEncoder)