python如何快速的判断一个key在json的第几层呢,并修改其value值
def find_and_modify_key(json_obj, target_key, new_value, current_level=1):if target_key in json_obj:print(f"找到 '{target_key}' 在第 {current_level} 层。")json_obj[target_key] = new_valuereturn current_level, json_objelse: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: return level, modified_objreturn None, json_obj
json_data = {"level1": {"level2": {"key_to_find": "old_value","another_key": "value"},"level2_2": {"key_to_find": "another_old_value"}},"single_level": "data"
}
target_key = "key_to_find"
new_value = "new_value"
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}'。")