python如何快速的判断一个key在json的第几层呢,并修改其value值

python如何快速的判断一个key在json的第几层呢,并修改其value值

python 复制代码
def find_and_modify_key(json_obj, target_key, new_value, current_level=1):
    # 检查当前层是否包含目标key
    if target_key in json_obj:
        print(f"找到 '{target_key}' 在第 {current_level} 层。")
        # 修改key的值
        json_obj[target_key] = new_value
        return current_level, json_obj
    else:
        # 否则,递归地搜索嵌套的字典
        for key, value in json_obj.items():
            if isinstance(value, dict):
                level, modified_obj = find_and_modify_key(value, target_key, new_value, current_level + 1)
                if level is not None:  # 如果找到了key
                    # 因为已经找到并修改了key,可以中断进一步的搜索
                    return level, modified_obj
        # 如果当前层及其子层都没有找到key,返回None
        return None, json_obj

# 示例JSON对象
json_data = {
    "level1": {
        "level2": {
            "key_to_find": "old_value",
            "another_key": "value"
        },
        "level2_2": {
            "key_to_find": "another_old_value"
        }
    },
    "single_level": "data"
}

# 要查找和修改的key及其新值
target_key = "key_to_find"
new_value = "new_value"

# 查找并修改key
level, modified_json = find_and_modify_key(json_data, target_key, new_value)

if level is not None:
    print(f"修改后的JSON数据:{modified_json}")
else:
    print(f"在JSON数据中未找到 '{target_key}'。")
相关推荐
心 一11 分钟前
Python 类型注解实战:`Optional` 与安全数据处理的艺术
服务器·python·安全
倔强青铜三23 分钟前
苦练Python第9天:if-else分支九剑
人工智能·python·面试
IRevers36 分钟前
【自动驾驶】经典LSS算法解析——深度估计
人工智能·python·深度学习·算法·机器学习·自动驾驶
倔强青铜三42 分钟前
苦练Python第8天:while 循环之妙用
人工智能·python·面试
不像程序员的程序媛1 小时前
redis的一些疑问
java·redis·mybatis
知其然亦知其所以然1 小时前
Java 面试高频题:GC 到底回收了什么、怎么回收、啥时候回收?
java·后端·面试
Z_W_H_1 小时前
【SpringBoot】 整合MyBatis+Postgresql
java·spring boot·后端
nbsaas-boot1 小时前
多租户架构下的多线程处理实践指南
java·开发语言·spring
倔强青铜三1 小时前
苦练Python第7天:布尔七日斩
人工智能·python·面试
倔强青铜三1 小时前
苦练Python第6天:数字魔法全解
人工智能·python·面试