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}'。")
相关推荐
zc.z2 小时前
JAVA实现:纯PCM格式音频转换成BASE64
java·音视频·pcm
mask哥3 小时前
力扣算法java实现汇总整理(上)
java·算法·leetcode
2301_809204704 小时前
JavaScript中严格模式use-strict对引擎解析的辅助.txt
jvm·数据库·python
zjy277774 小时前
mysql如何选择合适的索引类型_mysql索引设计实战
jvm·数据库·python
Aaswk4 小时前
Java Lambda 表达式与流处理
java·开发语言·python
是宇写的啊4 小时前
Spring AOP
java·spring
万邦科技Lafite4 小时前
京东item_get接口实战案例:实时商品价格监控全流程解析
java·开发语言·数据库·python·开放api·淘宝开放平台
Cyber4K5 小时前
【Python专项】进阶语法-系统资源监控与数据采集(1)
开发语言·python·php
Mr_pyx5 小时前
Spring AI 入门教程:Java开发者的AI应用捷径
java·人工智能·spring
Zephyr_06 小时前
Leedcode算法题
java·算法