Python操作JSON文件的知识点整理
作者:梦想橡皮擦 时间:2022-10-23 05:45:01
json 模块
Python 提供了内置的 json 模块来处理 JSON 格式的文件。
该模块主要分为读取和写入 JSON 文件。
读取 JSON
使用 json.load() 或 json.loads() 方法来读取 JSON 文件。
其中 json.load() 方法用于读取文件中的 JSON 数据,json.loads() 方法用于读取字符串中的 JSON 数据。
写入 JSON
使用 json.dump() 或 json.dumps() 方法来写入 JSON 文件。
其中 json.dump() 方法用于写入 JSON 数据到文件中,json.dumps() 方法用于将 JSON 数据转换为字符串。
基于上述内容可以总结一下: json.load() , json.loads() , json.dump() 和 json.dumps() 中的 s 都是字符串 string 的缩写。
读取与写入基本用法如下
提前准备一个 travel.json 文件,存放到 python 文件所在目录。
import json
# 读取json文件
with open('travel.json', 'r', encoding='utf-8') as f:
data = json.load(f)
# 写入json文件
with open('travel.new.json', 'w', encoding='utf-8') as f:
json.dump(data, f)
Tops:在使用 json.load() 和 json.loads() 读取 json 文件时,如果文件中存在格式错误,会抛出 ValueError 异常。
json 模块进阶用法
控制输出格式
在处理 JSON 文件时,还可以使用 json.dump() 方法的可选参数来控制输出的格式,例如:
sort_keys:按照键的字典序排序输出。
indent:缩进输出,可以指定缩进的空格数。
import json
# # 读取json文件
with open('travel.json', 'r', encoding='utf-8') as f:
data = json.load(f)
with open('travel.new.json', 'w', encoding='utf-8') as f:
json.dump(data, f, sort_keys=True, indent=4)
此时可以比对旧文件与新文件之间的差异,可以看到缩进关系产生了变化。
在 JSON 中存储 Python 特殊类型
如果你要在 json 中存储 python 特殊类型,例如 datetime,需要使用 json.JSONEncoder 类和 json.JSONDecoder 类来处理。
import json
from datetime import datetime
# 日期编码
class DateEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
return json.JSONEncoder.default(self, obj)
d = {'date': datetime.now()}
json_str = json.dumps(d, cls=DateEncoder)
print(json_str)
# 日期解码
class DateDecoder(json.JSONDecoder):
def __init__(self):
json.JSONDecoder.__init__(self, object_hook=self.dict_to_object)
def dict_to_object(self, d):
if 'date' in d:
d['date'] = datetime.strptime(d['date'], '%Y-%m-%d %H:%M:%S')
return d
data = json.loads(json_str, cls=DateDecoder)
print(data)
运行代码,可以得到编码和解码的输出。
{"date": "2023-01-27 21:24:46"}
{'date': datetime.datetime(2023, 1, 27, 21, 24, 46)}
对数据进行验证和清洗
JSON Schema 是一种用于验证 JSON 文档的标准,它可以用来确保 JSON 文档符合预期的格式。
jsonschema 模块需要提前安装,示例代码如下。
import json
import jsonschema
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number"}
},
"required": ["name", "age"]
}
data = '{"name": "梦想橡皮擦", "age": 28}'
try:
jsonschema.validate(json.loads(data), schema)
print("可用的JSON")
except jsonschema.exceptions.ValidationError as e:
print(e)
当你的 json 格式正确时,会输出相应的内容,输出错误信息,测试代码可以将 "required": ["name", "age"] 修改为 "required": ["name", "age" , "sex"]。
第三方模块
在处理 JSON 格式文件时还可以使用第三方库来更方便地操作,例如 pandas。
import pandas as pd
# 读取json文件
data = pd.read_json('travel.json')
# 写入json文件
data.to_json('travel.pandas.json')
还有其他第三方库也可以用来处理 JSON 格式文件,例如:
ijson:迭代读取大型 JSON 文件。
jsonpickle:支持将 Python 对象序列化为 JSON 格式。
jsonlines:简单而高效地读取和写入文本文件中的 JSON 数据。
simplejson:提供了一种比标准库更快的 JSON 解析器和生成器。
json-tricks:支持一些高级功能,例如压缩和迭代。
来源:https://blog.csdn.net/hihell/article/details/128773039
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
layer ui 导入文件之前传入数据的实例
PHP中的traits实现代码复用使用实例
Python基于Tensorflow2.X实现汽车油耗预测
![](https://img.aspxhome.com/file/2023/3/72743_0s.png)
Python编程基础之类和对象
![](https://img.aspxhome.com/file/2023/7/61437_0s.jpg)
IE9四大渲染引擎模式
![](https://img.aspxhome.com/file/UploadPic/20104/20/01-76s.jpg)
python函数默认参数使用避坑指南
![](https://img.aspxhome.com/file/2023/6/90296_0s.png)
php引用地址改变变量值的问题
扫盲大讲堂:SQL查询结果集对注入的影响及利用
pycharm查看变量值的4种方法汇总
![](https://img.aspxhome.com/file/2023/5/105025_0s.png)
详解Python中的正则表达式的用法
![](https://img.aspxhome.com/file/2023/0/78840_0s.jpg)
举例讲解Python中的死锁、可重入锁和互斥锁
mysql数据库你需要特别注意的23个事项
一个div层打开显示效果 js
定位?浮动?自适应?
![](https://img.aspxhome.com/file/UploadPic/20086/30/2008630142536281s.jpg)
python调试模式无响应解决案例
![](https://img.aspxhome.com/file/2023/0/101280_0s.jpg)
聊聊Python对CSV文件的读取与写入问题
![](https://img.aspxhome.com/file/2023/7/65527_0s.png)
python最小生成树kruskal与prim算法详解
![](https://img.aspxhome.com/file/2023/1/105001_0s.png)
6款jQuery图表插件[译]
![](https://img.aspxhome.com/file/UploadPic/20096/1/08200312t-81s.png)
部署Django到阿里云服务器教程示例
![](https://img.aspxhome.com/file/2023/8/64958_0s.png)
PyCharm设置每行最大长度限制的方法
![](https://img.aspxhome.com/file/2023/6/82806_0s.jpg)