Python 修改 JSON 文件
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,广泛应用于网络传输和数据存储。Python 提供了内置的 json
模块,方便我们处理 JSON 数据。本文将介绍如何使用 Python 修改 JSON 文件,包括读取和写入 JSON 数据。
读取 JSON 文件
要修改 JSON 文件,首先需要读取文件中的数据。可以使用 json
模块的 load()
函数将 JSON 数据加载到 Python 对象中。
下面是一个示例 JSON 文件 data.json
:
{
"name": "John",
"age": 30,
"city": "New York"
}
下面的代码演示了如何读取 JSON 文件并访问其中的数据:
import json
# 打开 JSON 文件
with open('data.json', 'r') as file:
# 加载 JSON 数据
data = json.load(file)
# 访问 JSON 数据
name = data['name']
age = data['age']
city = data['city']
# 打印数据
print(f"Name: {name}")
print(f"Age: {age}")
print(f"City: {city}")
运行上述代码会输出:
Name: John
Age: 30
City: New York
修改 JSON 数据
读取 JSON 数据后,我们可以对其中的数据进行修改。下面的代码演示了如何修改 data.json
文件中的 age
字段:
import json
# 打开 JSON 文件
with open('data.json', 'r') as file:
# 加载 JSON 数据
data = json.load(file)
# 修改数据
data['age'] = 40
# 保存修改后的 JSON 数据
with open('data.json', 'w') as file:
# 写入 JSON 数据
json.dump(data, file)
代码中,我们将 data['age']
的值修改为 40
,然后将修改后的 JSON 数据保存回 data.json
文件中。
格式化 JSON 输出
默认情况下,json.dump()
和 json.dumps()
函数生成的 JSON 数据是压缩的,不易阅读。我们可以使用 indent
参数指定缩进的空格数,使输出的 JSON 数据更加可读。
下面的代码演示了如何输出格式化的 JSON 数据:
import json
# 打开 JSON 文件
with open('data.json', 'r') as file:
# 加载 JSON 数据
data = json.load(file)
# 修改数据
data['age'] = 40
# 格式化输出 JSON 数据
formatted_json = json.dumps(data, indent=4)
# 打印格式化后的 JSON 数据
print(formatted_json)
上述代码中,我们使用 indent=4
参数将 JSON 数据缩进为 4 个空格。运行代码会输出格式化后的 JSON 数据:
{
"name": "John",
"age": 40,
"city": "New York"
}
总结
使用 Python 修改 JSON 文件可以通过 json
模块的 load()
函数读取 JSON 数据,然后对数据进行修改,最后通过 dump()
或 dumps()
函数将修改后的 JSON 数据写入文件或输出到控制台。
以上是使用 Python 修改 JSON 文件的简单示例。使用 Python 处理 JSON 数据的灵活性和简单性使得这一任务变得非常容易。希望本文对你有所帮助!