跳转到主内容
websoft网络软件专家 - 深耕网络技术,打造实用软件!

如何从 JSON 中安全提取嵌套在列表中的 "value" 字段

本文详解如何在 Python 中正确访问 JSON 数据中位于列表内的特定字段(如 properties 列表中 name 为 "textures" 的对象的 "value"),避免因类型误判(如将 list 当作 dict 访问)导致的 TypeError。 本文详解如何在 python 中正确访问 js on 数据中位于列表内的特定字段(如 `properties` 列表中 `name` 为 `"textures"` 的对象的 `"value"`),避免因类型误判(如将 list 当作 dict 访问)导致的 `typeerror`。 在处理外部 API 返回的 JSON 数据(例如 Mojang 的 Minecraft 用户资料接口)时,一个常见误区是忽略 JSON 结构中的容器类型差异:"properties" 字段实际是一个 列表(list) ,而非字典(dict)。因此,直接使用 skin_data["properties"]["value"] 会触发 TypeError: list indices must be integers or slices, not str —— 因为 Python 不允许用字符串键索引列表。 要正确提取目标值,需分三步操作: 确认字段存在且非空 :使用 .get() 安全访问,避免 KeyError; 遍历列表定位目标对象 :检查每个元素的 "name" 键是否匹配 "textures"; 提取并验证目标字段 :确保 "value" 键存在且非 None,再取值。 以下是健壮、生产可用的示例代码: Find JSON Path Online Easily find JSON paths within JSON objects using our intuitive Json Path Finder 下载
import requests import json # 构造请求 URL(注意:data['id'] 需已定义) 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 properties = skin_data.get("properties") if not isinstance(properties, list) or len(properties) == 0: print("Warning: 'properties' is missing, empty, or not a list.") skin_value = None else: skin_value = None for prop in properties: if (isinstance(prop, dict) and prop.get("name") == "textures" and "value" in prop): skin_value = prop["value"] break # 找到即退出,避免冗余遍历 if skin_value is None: print("Info: No 'textures' property with 'value' found.") else: print("Base64 textures value:", skin_value) except requests.exceptions.RequestException as e: print(f"Network error: {e}") except json.JSONDecodeError as e: print(f"Invalid JSON response: {e}")
✅ 关键注意事项 : 始终对 requests.get() 添加超时和异常处理,防止阻塞或崩溃; 使用 response. json () 而非 json.loads(response.text),前者内置编码检测与错误提示; 显式检查 prop 是否为 dict,增强对异常响应结构的容错性; 若需解码 Base64 纹理数据,后续可调用 base64.b64decode(skin_value); Mojang API 在未启用 ?unsigned=false 时可能不返回 "signature",但 "value" 仍存在——本逻辑不依赖 signature,故兼容两种模式。 掌握这种“先判断类型、再安全遍历、后精准匹配”的模式,可高效应对绝大多数嵌套 JSON 提取场景。

相关文章