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}'。")
相关推荐
uzong1 分钟前
程序员从大厂回重庆工作一年
java·后端·面试
kyle~6 分钟前
C++---value_type 解决泛型编程中的类型信息获取问题
java·开发语言·c++
小糖学代码3 小时前
LLM系列:1.python入门:3.布尔型对象
linux·开发语言·python
Data_agent3 小时前
1688获得1688店铺详情API,python请求示例
开发语言·爬虫·python
开心香辣派小星4 小时前
23种设计模式-15解释器模式
java·设计模式·解释器模式
Halo_tjn4 小时前
虚拟机相关实验概述
java·开发语言·windows·计算机
周杰伦fans4 小时前
pycharm之gitignore设置
开发语言·python·pycharm
摆烂z5 小时前
Docker与Jib(maven插件版)实战
java
RainbowSea5 小时前
从 Spring Boot 2.x 到 3.5.x + JDK21:一次完整的生产环境迁移实战
java·spring boot·后端
笨手笨脚の5 小时前
Spring Core常见错误及解决方案
java·后端·spring