You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何遍历多对象JSON数据 修复列表索引字符串TypeError

报错原因

你加载data.json得到的data是元素为字典的列表,不是字典类型。列表仅支持整数/切片作为索引,不支持"host"/"username"这类字符串作为索引,直接写data["host"]就会触发你看到的类型错误。
你的data实际结构是:

  • 最外层是列表,索引0、1分别对应两台服务器的配置字典
  • 每个内层字典才包含host、username、path三个字符串键对应的配置值
代码修改方案

第一步:确认正确加载JSON文件

先确保你是通过标准json库加载的文件,参考代码:

import json

# 读取加载json文件
with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

第二步:适配你要的zip循环写法

你需要先从每个配置字典里把所有host、username提取出来,组成长度一致的列表,再传入zip做并行遍历:

# 提前定义好你的remote可迭代对象,长度要和服务器配置数量一致
remote = [] # 替换成你实际的remote变量内容

# 提取对应字段的列表
all_hosts = [item["host"] for item in data]
all_usernames = [item["username"] for item in data]

# 执行循环
for remotes, host, username in zip(remote, all_hosts, all_usernames):
    # 这里写你的业务逻辑
    print(f"连接服务器:{username}@{host}")

更简便的遍历写法(非必须)

如果不强制要求用zip的传参格式,直接遍历外层列表即可,不用单独提取字段列表:

for idx, config in enumerate(data):
    current_remote = remote[idx] # 对应你原来的remotes变量
    host = config["host"]
    username = config["username"]
    # 后续业务逻辑

内容的提问来源于stack exchange,提问作者Yash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 18:31:12