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

Python中如何从API返回的data字典提取avatarUrl字符串?

问题描述

我有一段生成JSON数据(字典)的Python代码片段,无法从中获取avatarUrl字符串。代码如下:

def __init__(self, character_id):
    self.character_id = character_id
    self.character_data = self.get_character_data()
    print(self.character_data["id"])
    
def update(self):
    self.character_data = self.get_character_data()
    
def get_character_data(self):
    req = requests.get(f"https://character-service.dndbeyond.com/character/v5/character/{self.character_id}")
    #print("hello")
    if req.status_code != 200:
        return None
    try:
        j = req.json()
        if not "success" in j or not "data" in j:
            return None
        return j["data"]

    except ValueError:
        return None

返回的数据结构片段如下,我想要获取avatarUrl对应的URL以打开图片:

Press CTRL+C to quit
{'id': 108291017, 'userId': 118256620, 'username': 'sethirya', 'isAssignedToPlayer': True, 'readonlyUrl': 'https://dndbeyond.com/characters/108291017', 'decorations': {'avatarUrl': 'https://www.dndbeyond.com/avatars/21222/111/637708177497566513.jpeg?width=150&height=150&fit=crop&quality=95&auto=webp', 'frameAvatarUrl': 'https://www.dndbeyond.com/avatars/7169/957/637042612736861450.png', 'backdropAvatarUrl': '', 'frameAvatarDecorationKey': '558', 'frameAvatarId': 7169957, 'backdropAvatarDecorationKey': '407', 'backdropAvatarId': 61586, 'smallBackdropAvatarDecorationKey': '61587', 'smallBackdropAvatarId': 61587, 'largeBackdropAvatarDecorationKey': '61588', 'largeBackdropAvatarId': 61588, 'thumbnailBackdropAvatarDecorationKey': '61589', 'thumbnailBackdropAvatarId': 61589', 'themeColor': {'themeColorId': 429, 'themeColor': '#e5623e', 'backgroundColor': '#FEFEFE', 'name': 'Barbarian Fire', 'raceId': None, 'subRaceId': None, 'classId': 9, 'tags': ['Class Themes'], 'decorationKey': '429'}}, 'name': 'Raine', 'socialName': None, 'gender': 'Female/Non-binary', 'faith': '', 'age': 29, 'hair': '', 'eyes': 'gr'

我尝试用print函数获取所需内容,能打印其他字段,但获取avatarUrl时遇到问题,需要帮助。

解决方案

从数据结构能看到,avatarUrl嵌套在decorations字典里,不能直接通过self.character_data["avatarUrl"]获取,必须先访问decorations层级。

正确获取方式

在代码中,比如在__init__方法里添加打印代码:

print(self.character_data["decorations"]["avatarUrl"])

容错处理建议

为避免键不存在引发KeyError,可以用字典的get方法做兼容:

avatar_url = self.character_data.get("decorations", {}).get("avatarUrl", "默认图片URL")
print(avatar_url)

这样即使decorations或avatarUrl不存在,程序也不会崩溃,会返回你指定的默认值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 03:05:26