每日学习--JSON

每日学习--JSON,第1张

每日学习--JSON

问题: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

jsonpickledumps、dump、loads、loaddumps、dump、loads、load用于字符串和python数据类型间进行转换于python特有的类型和python的数据类型间进行转换可以在不同语言之间交换数据只在python之间使用只能序列化最基本的数据类型[(列表、字典、列表、字符串、数字)]可以序列化所有的数据类型,包括类,函数、日期 1. dumps 数据–>字符串
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)

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5443398.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存