Python处理json文件函数有哪些,怎么读写json文件
Admin 2022-05-21 群英技术资讯 513 次浏览
python处理json文本文件主要是以下四个函数:
函数 | 作用 |
---|---|
json.dumps | 对数据进行编码,将python中的字典 转换为 字符串 |
json.loads | 对数据进行解码,将 字符串 转换为 python中的字典 |
json.dump | 将dict数据写入json文件中 |
json.load | 打开json文件,并把字符串转换为python的dict数据 |
json.dumps / json.loads
数据转换对照:
json | python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
代码示例:
import json tesdic = { 'name': 'Tom', 'age': 18, 'score': { 'math': 98, 'chinese': 99 } } print(type(tesdic)) json_str = json.dumps(tesdic) print(json_str) print(type(json_str)) newdic = json.loads(json_str) print(newdic) print(type(newdic))
输出为:
<class 'dict'> {"name": "Tom", "age": 18, "score": {"math": 98, "chinese": 99}} <class 'str'> {'name': 'Tom', 'age': 18, 'score': {'math': 98, 'chinese': 99}} <class 'dict'>
json.dump / json.load
写入json的内容只能是dict类型,字符串类型的将会导致写入格式问题:
with open("res.json", 'w', encoding='utf-8') as fw: json.dump(json_str, fw, indent=4, ensure_ascii=False)
则json文件内容为:
"{\"name\": \"Tom\", \"age\": 18, \"score\": {\"math\": 98, \"chinese\": 99}}"
我们换一种数据类型写入:
with open("res.json", 'w', encoding='utf-8') as fw: json.dump(tesdic, fw, indent=4, ensure_ascii=False)
则生成的josn就是正确的格式:
{ "name": "Tom", "age": 18, "score": { "math": 98, "chinese": 99 } }
同理,从json中读取到的数据也是dict类型:
with open("res.json", 'r', encoding='utf-8') as fw: injson = json.load(fw) print(injson) print(type(injson))
{'name': 'Tom', 'age': 18, 'score': {'math': 98, 'chinese': 99}} <class 'dict'>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
本文主要介绍了Playwright中如何保持登录状态,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
这篇文章主要介绍了python 使用ctypes调用C/C++ dll详情,文章首先通过导入ctypes模块,加载C/C++ dll到python进程空间展开主题相关内容,需要的小伙伴可以参考一下
我们知道OpenCV是一个用于图像处理、分析、机器视觉方面的开源函数库,这篇文章就主要给大家分享的是有关OpenCv库怎样实现绘制简单的图,小编觉得挺实用的,对新手认识OpenCv库有一定的帮助,因此分享给大家做个参考,接下来一起跟随小编看看吧。
这篇文章主要为大家介绍了python程序的组织结构,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
这篇文章主要介绍了python使用OpenCV获取高动态范围成像HDR,如何使用不同曝光设置拍摄的多张图像创建高动态范围图像HDR,下文吗更详细的内容介绍,需要的小伙伴可以参考一下
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008