【文件处理】——字典写入json文件或TXT文件,读取文件中的字典&TypeError: Object of type ‘ndarray‘ is not JSON serializable错误解决方法
2023-09-11 14:21:45 时间
目录
一、将字典写入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))
参考:
相关文章
- Visual Studio 2012 编译错误【error C4996: 'scanf': This function or variable may be unsafe. 】的解决方案
- ios 开发file's owner以及outlet与连线的理解
- & 和 && 的区别
- 【IOS-COCOS2D-X 游戏开发之十一】NEW CCSPRITE()带来的错误&使用CCUSERDEFAULT及PVR.CCZ在COCOS2DX中要注意!
- 【HIBERNATE框架开发之六】HIBERNATE中ANNOTATION的关系映射&&组件映射!
- 【数组&双指针】leetcode 283. 移动零【简单】
- SQL Server 2008 R2用户'sa'登录失败(错误18456)
- 介绍一个能避免 CORS 错误的 Chrome 扩展 - Moesif Origin & CORS Changer
- 无法打开物理文件 "D:understructuredata _DAT.MDF"。操作系统错误 5:"5(拒绝访问。)"
- 错误1Files 的值“<<<<<<< .mine”无效。路径中具有非法字符。
- SQL Server 2008 R2用户'sa'登录失败(错误18456)
- 用户 'sa' 登录失败。原因: 该帐户被禁用。 (Microsoft SQL Server,错误: 18470)
- 华为OD机试 - Linux发行版的数量(Java & JS & Python)
- 华为OD机试 - 求满足条件的最长子串的长度(Java & JS & Python)
- 解决The type or namespace name 'XXXX' does not exist in the namespace 'XXXXXXXXX' 的错误
- C++:C++编程语言学习之数组/字符串/指针/引用/日期&I/O输入输出操作(I/O 库头文件/标准输出流cout/标准输入流cin/标准错误流/准日志流)的简介、案例应用之详细攻略
- RSAC 2019 | 威胁建模模型ATT&CK
- Django 之 admin组件使用&源码解析
- Android Studio & eclipse 调试技巧
- 65:内网安全-域环境&工作组&局域网探针方案——域信息收集就是要获取域里的用户都有哪些!多数操作需要管理员权限,比如mimikatz、nishang,所以事先做提权就非常关键了!!!
- 智能威胁分析之图数据构建——关联数据为环境数据图:如资产、资产脆弱性、文件信息、用户信息、IT系统架构信息等 行为数据图:如网络侧检测告警、终端侧检测告警、文件分析日志、应用日志、蜜罐日志、沙箱日志等 情报数据图:各类外部威胁情报 知识数据图:各类知识库(如ATT&CK,CAPEC,CWE)等
- Harmony OS — RadioButton & RadioContainer单选按钮&单选按钮组