如何修复使用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
相关产品推荐
相关产品推荐

