
本文详解 python 中访问 json 嵌套结构(尤其是列表内对象字段)的正确方法,重点解决因误将列表当字典索引导致的 typeerror,并提供健壮、可复用的提取逻辑。
本文详解 python 中访问 json 嵌套结构(尤其是列表内对象字段)的正确方法,重点解决因误将列表当字典索引导致的 typeerror,并提供健壮、可复用的提取逻辑。
在处理 Mojang 会话服务器返回的玩家资料 JSON(如 https://sessionserver.mojang.com/session/minecraft/profile/{id}?unsigned=false)时,开发者常需提取 properties 数组中 name: "textures" 对应的 value 字段(即 Base64 编码的皮肤纹理数据)。但直接使用 skin_data["properties"]["value"] 会触发 TypeError: list indices must be integers or slices, not str —— 根本原因在于:properties 是一个列表(list),而非字典(dict),无法用字符串键索引。
正确的做法是先确认该列表存在且非空,再遍历其中每个属性对象,按条件匹配目标项并安全提取字段。以下是推荐的生产级实现:
import requests
import json
skin_url = f"https://sessionserver.mojang.com/session/minecraft/profile/{data['id']}?unsigned=false"
try:
skin_r = requests.get(skin_url, timeout=5)
skin_r.raise_for_status() # 检查 HTTP 错误状态码
skin_data = skin_r.json() # 推荐用 .json() 替代 json.loads(skin_r.text)
# 安全获取 textures 的 value
textures_value = None
for prop in skin_data.get("properties", []):
if isinstance(prop, dict) and prop.get("name") == "textures":
textures_value = prop.get("value")
break # 找到即退出,避免冗余遍历
if textures_value:
print("Textures value (Base64):", textures_value[:64] + "..." if len(textures_value) > 64 else textures_value)
else:
print("Warning: 'textures' property not found or missing 'value' field.")
except requests.exceptions.RequestException as e:
print(f"Network error fetching profile: {e}")
except json.JSONDecodeError as e:
print(f"Invalid JSON response: {e}")
except KeyError as e:
print(f"Missing expected field in JSON: {e}")✅ 关键要点与最佳实践:
- 使用 skin_data.get("properties", []) 替代直接索引,避免 KeyError;
- 显式检查 isinstance(prop, dict) 防御性编程,确保列表元素为字典;
- 用 .get("name") 和 .get("value") 安全取值,避免 KeyError;
- 添加 timeout 和 raise_for_status() 提升网络请求鲁棒性;
- 优先调用 response.json() 而非 json.loads(response.text),它自动处理编码与异常;
- 若需支持多属性或动态名称,可封装为可复用函数:
def get_property_value(data, target_name, field="value"):
"""从 properties 列表中查找指定 name 的对象,并返回其指定字段值"""
for prop in data.get("properties", []):
if isinstance(prop, dict) and prop.get("name") == target_name:
return prop.get(field)
return None
# 使用示例
value = get_property_value(skin_data, "textures", "value")掌握这种“列表→对象→字段”的三级安全访问模式,不仅能解决 Mojang API 场景,也适用于任何含数组嵌套结构的 JSON 解析任务。










