Python处理json文件函数有哪些,怎么读写json文件
Admin 2022-05-21 群英技术资讯 641 次浏览
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进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
这篇文章主要介绍了Python的3种运行方式:命令行窗口、Python解释器、IDLE的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
这篇文章主要为大家详细介绍了python绘制箱型图,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
缺失值可能是数据科学中最不受欢迎的值,然而,它们总是在身边。忽略缺失值也是不合理的,因此我们需要找到有效且适当地处理它们的方法。本文总结了四个Python查询缺失值的方法,需要的可以参考一下
List(列表)作为python中使用最频繁的数据类型,如果能够把列表掌握,那么对于Python的掌握是有很大帮助的。
IndentationError:unexpectedindent Python中强制缩进,,IndentationError:unexpectedindent缩进错误这类错误非常常见,一般都是由于tab在不同的平台上占用长度不同导致,有些事程序员自己直接使用空格或其他来顶替tab。解决办法非常简单,在所在平台上使用标准的tab进行缩进,就OK了。Unicode
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008