Python读取JSON文件获取remotes字段运行报错如何解决
报错原因
- 核心错误:你的JSON文件顶层是数组结构,对应Python加载后得到的是
list类型,不是dict类型。直接对列表执行destinations['remotes']操作会触发TypeError: list indices must be integers or slices, not str——remotes是列表内第3个元素(索引为2)的键,并非顶层结构的键。 - 其余隐性问题:
- 代码未导入
json模块,运行时会直接触发名称错误 - 遍历路径时直接修改循环临时变量
destination不会改动原列表内容:Python字符串是不可变对象,临时变量重新赋值不会同步修改原列表存储的值 - 手动调用
open()打开文件未做异常兜底,容易出现文件句柄泄漏 - 路径拼接用到的
year/month/date变量未提前定义,运行时会触发名称错误
- 代码未导入
修正代码
import json from datetime import datetime # 按需替换年月日取值逻辑,示例取当前系统日期 now = datetime.now() year = f"{now.year}" month = f"{now.month:02d}" date = f"{now.day:02d}" # 用上下文管理器自动管理文件开闭,无需手动调用close() with open('/path/to/json1.json', 'r', encoding='utf-8') as json_file: config_list = json.load(json_file) # 固定位置取remotes的写法(对应你当前JSON结构) remotes = config_list[2]['remotes'] # 如果后续JSON元素顺序可能变动,用遍历查找的写法更稳妥 # remotes = [] # for item in config_list: # if isinstance(item, dict) and 'remotes' in item: # remotes = item['remotes'] # break # 拼接完整目标路径 processed_destinations = [] for dest in remotes: # 自动去除路径末尾多余斜杠,避免出现双斜杠问题 full_path = f"{dest.rstrip('/')}/{year}/{month}/{date}" processed_destinations.append(full_path) # 后续可直接使用processed_destinations做备份操作 print(processed_destinations)
内容的提问来源于stack exchange,提问作者Nova
相关产品推荐
相关产品推荐

