您当前的位置:首页 > IT编程 > python
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:详解python读写json文件

51自学网 2022-02-21 10:45:06
  python
这篇教程详解python读写json文件写得很实用,希望能帮到您。

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 jsontesdic = {    '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'>

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注51zixue.net的更多内容!


详解Python中的字符串常识
Python线程编程之Thread详解
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。