20 天学 Python 文件操作:Day 9 JSON 文件操作
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,广泛用于 API 和配置文件中。Python 提供了内置的 json 模块,帮助我们轻松地读取、写入和操作 JSON 数据。今天,我们将学习如何高效地处理 JSON 文件。
1. JSON 格式简介
JSON 是基于键值对的结构化数据格式,类似于 Python 的字典。以下是一个 JSON 示例:
{
"name": "Alice",
"age": 25,
"skills": ["Python", "Machine Learning"]
}
2. 读取 JSON 文件
使用 json.load 从文件中加载 JSON 数据。
示例:读取 JSON 文件
假设有一个文件 data.json,内容如下:
{
"name": "Alice",
"age": 25,
"skills": ["Python", "Machine Learning"]
}
import json
def read_json(file_path):
with open(file_path, 'r') as f:
data = json.load(f)
print("读取的 JSON 数据:", data)
return data
# 示例
data = read_json("data.json")
3. 写入 JSON 文件
使用 json.dump 将数据写入 JSON 文件。
示例:写入 JSON 文件
import json
def write_json(file_path, data):
with open(file_path, 'w') as f:
json.dump(data, f, indent=4)
print(f"数据已写入到 {file_path}")
# 示例
data = {
"name": "Bob",
"age": 30,
"skills": ["Java", "Spring"]
}
write_json("output.json", data)
注意:参数 indent=4 用于格式化输出,使 JSON 更易读。
4. 修改 JSON 数据
可以先加载 JSON 数据,进行修改后再保存。
示例:修改 JSON 文件
import json
def update_json(file_path, key, value):
with open(file_path, 'r') as f:
data = json.load(f)
data[key] = value
with open(file_path, 'w') as f:
json.dump(data, f, indent=4)
print(f"文件 {file_path} 中的键 '{key}' 已更新为 '{value}'")
# 示例
update_json("data.json", "age", 28)
5. JSON 字符串操作
除了文件操作,json 模块还支持 JSON 字符串的解析和生成。
从 JSON 字符串解析数据
def parse_json_string(json_string):
data = json.loads(json_string)
print("解析的 JSON 数据:", data)
return data
# 示例
json_string = '{"name": "Charlie", "age": 22}'
data = parse_json_string(json_string)
将数据转换为 JSON 字符串
def generate_json_string(data):
json_string = json.dumps(data, indent=4)
print("生成的 JSON 字符串:")
print(json_string)
return json_string
# 示例
data = {"name": "Diana", "age": 35}
json_string = generate_json_string(data)
6. 练习任务
- 编写一个函数 merge_json_files(file1, file2, output_file),将两个 JSON 文件的数据合并后保存到新的 JSON 文件。
- 编写一个函数 filter_json(file_path, key, value),过滤 JSON 文件中包含特定键值的数据并返回。
示例代码框架
def merge_json_files(file1, file2, output_file):
with open(file1, 'r') as f1, open(file2, 'r') as f2:
data1 = json.load(f1)
data2 = json.load(f2)
merged_data = {**data1, **data2}
with open(output_file, 'w') as f:
json.dump(merged_data, f, indent=4)
print(f"文件已合并到 {output_file}")
def filter_json(file_path, key, value):
with open(file_path, 'r') as f:
data = json.load(f)
filtered_data = {k: v for k, v in data.items() if v.get(key) == value}
return filtered_data
通过今天的学习,你已经掌握了如何读取、写入、修改和解析 JSON 数据。明天我们将学习文件权限与安全性相关的操作,敬请期待!