python怎么修改json文件内容

583
2023/11/23 17:08:28
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要修改JSON文件的内容,可以按照以下步骤进行:

  1. 使用json模块的load函数加载JSON文件,并将其解析为Python对象。例如:
import json

with open('data.json', 'r') as file:
    data = json.load(file)
  1. 对Python对象进行修改。你可以像操作任何其他Python对象一样对其进行修改,例如添加、删除或修改键值对。例如:
data['key'] = 'new value'
data.pop('another_key')
  1. 使用json模块的dump函数将修改后的Python对象重新转换为JSON格式,并将其写入文件。例如:
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)

# 修改数据
data['key'] = 'new value'
data.pop('another_key')

# 保存修改后的数据到JSON文件
with open('data.json', 'w') as file:
    json.dump(data, file)

请确保将代码中的"data.json"替换为你实际使用的JSON文件的路径。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: python怎么定义多行字符串