问题:Object of type Tensor is not JSON serializable
json_str = json.dumps(image_dict) with open('../yy/Data/weibo/image_dict.json', 'w') as json_file: json_file.write(json_str)
原因:json.dumps函数发现字典里面有bytes类型的数据,无法编码。
解决方法:将bytes类型的数据转化成str类型;或者用pickle
【我字典里存的图片对应的tensor用不了json.dumps转换成字符串,只能强制转换】
# json_str = json.dumps(image_dict) with open('../yy/Data/weibo/image_dict.json', 'w') as json_file: json_file.write(str(image_dict))
补充:
json和pickle是用于序列化的两个模块,都有四个功能:
dumps、dump、loads、load
import json test_dict = {'bigberg': [7600, {1: [['iPhone', 6300], ['Bike', 800], ['shirt', 300]]}]} print(test_dict) print(type(test_dict)) #dumps 将数据转换成字符串 json_str = json.dumps(test_dict) print(json_str) print(type(json_str))2.dump: 将数据–>json文件
with open("../config/record.json","w") as f: json.dump(new_dict,f) print("加载入文件完成...")3.loads: 字符串–>字典
new_dict = json.loads(json_str) print(new_dict) print(type(new_dict))4.load:打开文件并把字符串–>数据类型
with open("../config/record.json",'r') as load_f: load_dict = json.load(load_f) print(load_dict) load_dict['smallberg'] = [8200,{1:[['Python',81],['shirt',300]]}] print(load_dict) with open("../config/record.json","w") as dump_f: json.dump(load_dict,dump_f)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)