Python如何修改嵌套字典值及JSON数组内指定字段的属性值
解答
要不要遍历Commands数组?
需要。因为你无法提前预知Commands数组下各字典的排列顺序,没办法通过固定索引直接定位到目标条目,所以必须至少遍历一次数组完成匹配。
顺序不固定时的定位修改方案
你可以根据自己的使用场景选以下两种方案:
方案1:单次遍历直接修改
适合只需要修改一次的场景,逻辑简单直接:
import json # 读取JSON文件并转为Python字典 with open("你的配置文件路径.json", "r", encoding="utf-8") as f: config = json.load(f) # 定义需要修改的键值映射:目标字段名 -> 新值 update_rule = { "emailOrPhone": "替换为你的新邮箱", "username": "替换为你的新用户名", "password": "替换为你的新密码" } # 遍历Commands数组匹配目标 for cmd_item in config["Commands"]: # 先过滤出type类型的命令,避免误改open等其他命令 if cmd_item.get("Command") != "type": continue target = cmd_item.get("Target", "") # 匹配Target为name=xxx格式的条目 if target.startswith("name="): target_key = target.split("=")[1] if target_key in update_rule: cmd_item["Value"] = update_rule[target_key] # 把修改后的字典写回JSON文件(不需要保存可以跳过这步) with open("修改后的配置文件路径.json", "w", encoding="utf-8") as f: json.dump(config, f, indent=2, ensure_ascii=False)
方案2:先构建映射字典再修改
适合需要多次查询、修改条目的场景,一次遍历构建索引后后续操作不需要再遍历:
# 接上面读取config后的步骤 # 构建 目标字段名 -> 对应Command字典 的映射 cmd_index = {} for cmd_item in config["Commands"]: if cmd_item.get("Command") == "type" and cmd_item.get("Target", "").startswith("name="): target_key = cmd_item["Target"].split("=")[1] cmd_index[target_key] = cmd_item # 直接修改对应条目,不需要再次遍历 cmd_index["emailOrPhone"]["Value"] = "新邮箱@test.com" cmd_index["username"]["Value"] = "新用户名123" cmd_index["password"]["Value"] = "新密码xxx"
注意事项
- 如果你的
Target字段格式不固定为name=xxx,可以直接用完整字符串匹配:if cmd_item["Target"] == "name=emailOrPhone",匹配准确性更高 - 匹配前先判断
Command字段为type,可以避免误改其他类型的命令条目
内容的提问来源于stack exchange,提问作者Win
相关产品推荐
相关产品推荐

