【文件处理】——字典写入json文件或TXT文件,读取文件中的字典&TypeError: Object of type ‘ndarray‘ is not JSON serializable错误解决方法

目录

一、将字典写入json文件

二、json文件中读取字典

三、将字典写入TXT文件中

四、从TXT中读取字典

五、解决字典含数组存入json文件失败的方法

1、存入前将数组变成列表

2、扩展类方法


 


一、将字典写入json文件

import json

test_dict = {
    'version': "1.0",
    'explain': {
        'used': True,
        'details': "this is for josn test",
  }
}

#将字典转换为字符串形式
json_str = json.dumps(test_dict, indent=4)#注意这个indent参数,可以保存字典的缩进格式,否则为一行

with open('test_data.json', 'w') as json_file:
     json_file.write(json_str)

二、json文件中读取字典

with open('test_data.json', 'r') as json_file:
	dic = json.load(json_file)

三、将字典写入TXT文件中

import json

dic = {  
    'andy':{  
        'age': 23,  
        'city': 'beijing',  
        'skill': 'python'  
    },  
    'william': {  
        'age': 25,  
        'city': 'shanghai',  
        'skill': 'js'  
    }  
}  

js = json.dumps(dic)   
file = open('test.txt', 'w')  
file.write(js)  
file.close()  

四、从TXT中读取字典

import json

file = open('test.txt', 'r') 
js = file.read()
dic = json.loads(js)   
print(dic) 
file.close() 

五、解决字典含数组存入json文件失败的方法

因为json无法序列化

1、存入前将数组变成列表

array.tolist()

2、扩展类方法

class NpEncoder(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()
        else:
            return super(NpEncoder, self).default(obj)

将上述代码添加到你的代码中,然后改成json.dumps(data, cls=NpEncoder) 

TypeError: Object of type 'ndarray' is not JSON serializable

from collections import defaultdict
import json
import numpy as np

class NpEncoder(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()
        else:
            return super(NpEncoder, self).default(obj)


video = defaultdict(list)
video["label"].append("haha")
video["data"].append(234)
video["score"].append(0.3)
video["label"].append("xixi")
video["data"].append(123)
video["score"].append(0.7)

test_dict = {
    'version': "1.0",
    'results': (np.zeros((2,3))),
    'explain': {
        'used': True,
        'details': "this is for josn test",
  }
}
print(test_dict)
json_str = json.dumps(test_dict, indent=4,cls=NpEncoder)#注意这个indent参数
with open('test_data.json', 'w') as json_file:
     json_file.write(json_str)

with open('test_data.json', 'r') as json_file:
	dic = json.load(json_file)
print(type(dic))

参考:

https://blog.csdn.net/li532331251/article/details/78203438

https://blog.csdn.net/BobChill/article/details/83864285

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有情怀的机械男

你的鼓励将是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值