Python如何从加密货币价格JSON文件提取percentage值并修复TypeError
报错原因
你加载得到的data是字典结构,顶层key为交易对名称字符串(如ETH/BTC),直接遍历data得到的是字符串类型的key,无法使用字典索引方式取值,因此触发TypeError: string indices must be integers错误。
提取字段代码实现
你需要的percentage字段在每个交易对对应的字典首层,若要提取info下的priceChangePercent字段可参考注释调整:
import json with open('balance.txt', encoding='utf-8') as json_file: data = json.load(json_file) percentage_result = [] for trade_pair, pair_data in data.items(): # 提取首层percentage字段 current_percent = pair_data['percentage'] # 若要提取info下的priceChangePercent,替换为以下语句 # current_percent = pair_data['info']['priceChangePercent'] percentage_result.append(current_percent) print(f"{trade_pair} 涨跌幅: {current_percent}%") # 输出所有提取到的百分比数值 print("所有币种涨跌幅列表:", percentage_result)
全层级搜索字段通用方案
如果不确定目标字段的所在层级,可以使用递归方法遍历JSON所有节点提取:
def search_key(data, target_key): res = [] if isinstance(data, dict): for key, value in data.items(): if key == target_key: res.append(value) elif isinstance(value, (dict, list)): res.extend(search_key(value, target_key)) elif isinstance(data, list): for item in data: res.extend(search_key(item, target_key)) return res # 调用方法搜索所有percentage字段 all_percentage = search_key(data, 'percentage') print(all_percentage)
内容的提问来源于stack exchange,提问作者rohan gala
相关产品推荐
相关产品推荐

