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

如何修复使用Telegram bot发送JSON格式消息时出现的AttributeError错误

修复方案

报错原因

你直接遍历了从JSON加载得到的顶层data字典,Python遍历字典默认返回的是字典的键(字符串类型,比如你的JSON里第一个键是name_of_coin),你对字符串调用只有字典才有的get方法,自然会抛出属性错误。你需要的交易对数据全部存储在data下的marketPairs数组中,遍历这个数组即可拿到预期的字典对象。

修复后代码

with open(file_path) as file:
    data = json.load(file)

# 遍历marketPairs数组而不是顶层data字典
for item in data.get("marketPairs", []):
    card = f'{hbold("ExchangeName: ")}{(item.get("exchange_name"))}\n' \
    f'{hbold("MarketUrl: ")}{(item.get("market_url"))}\n' \
    f'{hbold("Price: ")}{(item.get("price"))}\n' \
    f'{hbold("LastUpdated: ")}{(item.get("last_update"))}\n' \
    f'{hbold("ExchangeId: ")}{(item.get("exchange_id"))}\n' 

    await message.answer(card)

这里用data.get("marketPairs", [])是为了兼容JSON结构异常的情况,如果marketPairs字段不存在,会默认返回空数组,避免遍历报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:54:03