详解python读写json文件
作者:liulanba 时间:2022-11-01 16:18:53
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'>
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注脚本之家的更多内容!
来源:https://blog.csdn.net/liulanba/article/details/121963892
标签:python,读写,json,文件


猜你喜欢
asp如何在ADO中使用存储查询?
2010-06-17 12:52:00
深入理解go slice结构
2024-04-26 17:27:07

网购中的商品评价与口碑传播-译
2010-07-09 13:44:00

利用python在excel里面直接使用sql函数的方法
2023-10-15 00:34:57

使用pandas中的DataFrame数据绘制柱状图的方法
2023-08-10 20:59:40

SQL Server DBA日常检查常用SQL
2024-01-12 21:47:49
Python基于SMTP协议实现发送邮件功能详解
2022-07-17 00:31:00

使用Python获取网段IP个数以及地址清单的方法
2021-02-25 03:28:21

利用Python批量生成任意尺寸的图片
2021-02-14 11:20:12

使用版本控制原因及Git与Subversion介绍
2023-12-09 22:29:18
Linux系统(CentOS)下python2.7.10安装
2021-04-02 19:27:50

mysql 超大数据/表管理技巧
2024-01-16 22:14:05
js检测浏览器语种,适合于多语言版本的站点
2007-09-12 19:16:00
浅谈Python type的使用
2021-05-17 05:58:59
pytorch模型保存与加载中的一些问题实战记录
2021-09-03 21:41:50

python3.5 + PyQt5 +Eric6 实现的一个计算器代码
2021-02-27 17:00:28

vue中iframe的使用及说明
2024-05-13 09:37:25
System.Data.OleDb.OleDbDataAdapter与System.Data.OleDb.OleDbDataReader的区别是什么?
2009-10-29 12:17:00
python打开windows应用程序的实例
2021-08-22 09:49:40
JQuery中对Select的option项的添加、删除、取值
2024-04-22 12:59:14