Python对JSON数据操作
在Python中,对JSON数据进行增删改查及加载保存操作,主要通过内置的json
模块实现。
一、基础操作
1. 加载JSON数据
• 从文件加载
使用json.load()
读取JSON文件并转换为Python对象(字典/列表):
import json
with open('data.json', 'r', encoding='utf-8') as f:data = json.load(f)
• 从字符串加载
使用json.loads()
将JSON字符串解析为Python对象:
json_str = '{"name": "Alice", "age": 30}'
data = json.loads(json_str)
2. 保存JSON数据
• 保存到文件
使用json.dump()
将Python对象写入JSON文件:
with open('data.json', 'w') as f:json.dump(data, f, indent=4) # indent参数格式化输出
• 转换为字符串
使用json.dumps()
生成JSON字符串:
json_str = json.dumps(data, ensure_ascii=False) # 处理中文字符
二、数据操作
1. 查询数据
通过字典键或列表索引访问数据:
# 示例JSON结构:{"students": [{"id": 1, "name": "Alice"}, ...]}
print(data['students'][0]['name']) # 输出:Alice
2. 新增数据
向列表或字典中添加新条目:
# 添加新学生
new_student = {"id": 4, "name": "David"}
data['students'].append(new_student) # 列表添加
3. 修改数据
直接修改字典或列表的值:
# 修改第一个学生的年龄
data['students'][0]['age'] = 25
4. 删除数据
使用del
或pop()
删除条目:
# 删除第一个学生
del data['students'][0] # 或 data['students'].pop(0)
三、进阶操作
1. 处理复杂结构
• 嵌套数据操作
通过逐层访问修改嵌套数据:
data['root']['child']['key'] = 'value' # 修改多层嵌套数据
• 条件查询与修改
结合循环和条件语句:
# 将所有年龄大于20的学生标记为成人
for student in data['students']:if student['age'] > 20:student['is_adult'] = True #
2. 处理特殊数据类型
• 日期/时间对象
自定义编码器处理非标准类型:
from datetime import datetime
def custom_encoder(obj):if isinstance(obj, datetime):return obj.isoformat()raise TypeError("Type not serializable")json_str = json.dumps(data, default=custom_encoder)
• 自定义解码器
反序列化时还原特殊类型:
def custom_decoder(dct):if 'timestamp' in dct:dct['timestamp'] = datetime.fromisoformat(dct['timestamp'])return dct
data = json.loads(json_str, object_hook=custom_decoder) #
四、注意事项
-
文件模式:
•'r'
用于读取,'w'
会覆盖原文件,'r+'
可读写但不保留旧内容。 -
编码问题:
处理中文时需设置ensure_ascii=False
。