目录

一、将字典写入json文件

二、json文件中读取字典

三、将字典写入TXT文件中

四、从TXT中读取字典

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

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

2、扩展类方法



一、将字典写入json文件

import jsontest_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 jsondic = {  '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 jsonfile = 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 npclass 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

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

  1. 成功解决TypeError: Object of type 'ndarray' is not JSON serializable

    解决问题 TypeError: Object of type 'ndarray' is not JSON serializable 解决方法 def default(self, obj):if isi ...

  2. Flask API TypeError: Object of type 'Response' is not JSON serializable

    Flask API TypeError: Object of type 'Response' is not JSON serializable 错误代码: session['image'] = str ...

  3. TypeError: Object of type set is not JSON serializable

    今天运行flask项目突然报TypeError: Object of type set is not JSON serializable错误,上网搜了一下 该对象是set形式,json序列不支持,回到 ...

  4. 返回 JSON 格式数据报错:TypeError: Object of type set is not JSON serializable

    在做 flask 项目的时候需要返回一个 JSON 数据,运行的过程中却报错:TypeError: Object of type set is not JSON serializable 报错位置如下 ...

  5. 记录:TypeError: Object of type int32 is not JSON serializable。

    rect_list = list()...rect_list.append(rect1)rect_list.append(rect2)...rsp = {'rect-list': rect_list} ...

  6. Object of type 'ndarray' is not JSON serializable

    Object of type 'ndarray' is not JSON serializable import numpy as np import jsonar=np.asarray([345,4 ...

  7. labelme2coco问题:TypeError: Object of type 'int64' is not JSON serializable

    最近在做MaskRCNN 在自己的数据(labelme)转为COCOjson格式遇到问题:TypeError: Object of type 'int64' is not JSON serializa ...

  8. TypeError: Object of type 'datetime' is not JSON serializable

    json序列化时间对象的时候报错: TypeError: Object of type 'datetime' is not JSON serializable 解决办法 重写json序列化类 # -* ...

  9. Python TypeError: Object of type ‘Decimal‘ is not JSON serializable 类型错误 无法json

    场景:今天使用python 查询了一个MYSQL 数据库的信息  数据库的字段为decimal 类型 我将结果进行json.dumps 报错 TypeError: Object of type 'De ...

最新文章

  1. Pycharm中tensorflow框架下tqdm的安装
  2. 【Verilog HDL 训练】第 11 天(分频电路)
  3. 人工智能学习知识框架(知识点、实际应用)-思维导图汇总-xmind原图
  4. STM32之CAN---工作/测试模式浅析
  5. thinkphp5部署nginx服务上多站点解决方案!
  6. MSSQLSERVER服务不能启动
  7. 数据库面试题之PL/SQL面试题
  8. 为什么远程计算机后会黑屏,解决Win10电脑远程桌面黑屏的问题
  9. 声笔飞码6.00版使用指南
  10. linux 找出僵尸进程,linux 查看僵尸进程
  11. 如何看懂财务报表|介绍
  12. android 友盟统计功能,Android应用中添加友盟统计
  13. Invalid argument: Subshape must have computed start >= end since stride is negative, but is 0 and 2
  14. 大学刚毕业,用10000小时,走进字节跳动拿了offer
  15. 学习笔记2:高精度地图
  16. 十一长假我肝了这本超硬核PDF,现决定开源!!
  17. 合约机乱象频出,运营商利益如何才能得到保障?
  18. 小米电视2 android版本,教你如何打开小米电视2 1.1.25版本的adb调试
  19. Unity3D 人称设置(第一人称视角、第三人称视角)
  20. iar 预编译会把非条件的去掉_SkyIAR(简单高效的IDEAHCIRAID解决方案)v1.2 [2012.8.14]...

热门文章

  1. (转)SystemProcessesAndThreadsInformation
  2. 微软推出免费在线系统诊断工具--不用手动下载
  3. iOS开发-证书问题精析~
  4. 自执行匿名函数剖析整理
  5. Swift傻傻分不清楚系列(十一)类和结构体
  6. 【SPOJ 694】Distinct Substrings (更直接的求法)
  7. 陈天艺1636050045假设跑步者1小时40分钟35秒跑了24英里。编写一个程序显示每小时以公里为单位的平均速度值...
  8. IDEA注册jar包使用和常用插件
  9. 利用Vagrant and VirtualBox搭建core os环境
  10. hdu 4279 Number