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

Python从JSON的properties数组中获取value字段报错,如何解决?

问题:获取Mojang玩家皮肤数据中的value字段

需要从如下JSON结构中提取value字段:

{
    "id": "<profile identifier>",
    "name": "<player name>",
    "properties": [ 
        {
            "name": "textures",
            "value": "<base64 string>",
            "signature": "<base64 string; signed data using Yggdrasil's private key>" // Only provided if ?unsigned=false is appended to url
        }
    ],
    "profileActions": []
}

当前代码尝试直接访问,但运行报错:

skin_url = "https://sessionserver.mojang.com/session/minecraft/profile/" + data['id'] + "?unsigned=false"
skin_r = requests.get(skin_url)
skin_data = json.loads(skin_r.text)
print(skin_data["properties"]["value"])

错误信息:

Traceback (most recent call last):
  File "C:\Users\myname\Python\numbers.py", line 15, in <module>
    print(skin_data["properties"]["value"])
          ~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^
TypeError: list indices must be integers or slices, not str

解决方案

错误原因

skin_data["properties"]是列表类型(对应JSON中的数组),不是字典,因此不能直接用字符串"value"作为索引,必须先通过整数索引取出列表中的元素,再访问字典的key。

修复代码(简洁版)

直接取列表第一个元素(Mojang返回的properties通常只有一个textures条目):

skin_url = "https://sessionserver.mojang.com/session/minecraft/profile/" + data['id'] + "?unsigned=false"
skin_r = requests.get(skin_url)
skin_data = json.loads(skin_r.text)
# 先访问列表的第一个元素,再取value字段
print(skin_data["properties"][0]["value"])

鲁棒版代码(推荐)

如果担心properties中存在多个条目,可通过遍历找到name为textures的条目:

skin_url = "https://sessionserver.mojang.com/session/minecraft/profile/" + data['id'] + "?unsigned=false"
skin_r = requests.get(skin_url)
skin_data = json.loads(skin_r.text)

# 遍历properties列表,匹配目标条目
for prop in skin_data["properties"]:
    if prop["name"] == "textures":
        print(prop["value"])
        break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 23:25:54