要使用Python将多个对象添加到JSON文件中的单个数组中,可以按照以下步骤进行操作:
import json
with open('data.json', 'r') as file:
data = json.load(file)
new_object = {
"name": "John",
"age": 30,
"city": "New York"
}
data.append(new_object)
with open('data.json', 'w') as file:
json.dump(data, file)
完整的代码示例:
import json
# 读取JSON文件内容
with open('data.json', 'r') as file:
data = json.load(file)
# 创建要添加的对象
new_object = {
"name": "John",
"age": 30,
"city": "New York"
}
# 将对象添加到数组中
data.append(new_object)
# 将更新后的数据写入JSON文件
with open('data.json', 'w') as file:
json.dump(data, file)
这样就可以将多个对象添加到JSON文件中的单个数组中了。请注意,代码中的data.json
是JSON文件的路径,根据实际情况进行修改。
领取专属 10元无门槛券
手把手带您无忧上云