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}'。")
相关推荐
码界筑梦坊8 分钟前
353-基于Python的大湾区气候数据可视化分析系统
开发语言·python·信息可视化·数据分析·django·vue·毕业设计
Magic--8 分钟前
深入解析管道:最基础的进程间通信(IPC)实现
java·服务器·unix
如何原谅奋力过但无声30 分钟前
【chap11-动态规划(上 - 基础题目&背包问题)】用Python3刷《代码随想录》
数据结构·python·算法·动态规划
架构师沉默37 分钟前
为什么国外程序员都写独立博客,而国内都在公众号?
java·后端·架构
带刺的坐椅43 分钟前
SolonCode v2026.4.1 发布(比 ClaudeCode 简约的编程智能体)
java·ai·llm·agent·solon-ai·claudecode·soloncode
殷紫川43 分钟前
从单体到亿级流量:登录功能全场景设计指南,踩过的坑全给你填平了
java
Filwaod44 分钟前
Cursor+IDEA开发问题
java·idea·cursor
云姜.1 小时前
JSON Schema使用
python·json
Sunshine for you1 小时前
使用Flask快速搭建轻量级Web应用
jvm·数据库·python
爱丽_1 小时前
Spring 事务:传播行为、失效场景、回滚规则与最佳实践
java·后端·spring