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}'。")
相关推荐
一晌小贪欢24 分钟前
Python 测试利器:使用 pytest 高效编写和管理单元测试
python·单元测试·pytest·python3·python测试
小文数模25 分钟前
2026年美赛数学建模C题完整参考论文(含模型和代码)
python·数学建模·matlab
惊讶的猫27 分钟前
探究StringBuilder和StringBuffer的线程安全问题
java·开发语言
jmxwzy30 分钟前
Spring全家桶
java·spring·rpc
Halo_tjn33 分钟前
基于封装的专项 知识点
java·前端·python·算法
Hgfdsaqwr1 小时前
掌握Python魔法方法(Magic Methods)
jvm·数据库·python
weixin_395448911 小时前
export_onnx.py_0130
pytorch·python·深度学习
s1hiyu1 小时前
使用Scrapy框架构建分布式爬虫
jvm·数据库·python
2301_763472461 小时前
使用Seaborn绘制统计图形:更美更简单
jvm·数据库·python
Fleshy数模1 小时前
从数据获取到突破限制:Python爬虫进阶实战全攻略
java·开发语言