如何从嵌套字典构建类?基于Bittrex API返回的JSON数据
基于嵌套JSON构建类的解决方案
嘿,作为编程新手能想到用类来结构化从API获取的嵌套数据,这思路真的很棒!完全不用为格式或术语的问题担心,咱们一步步把这个问题搞定~
方案1:使用Python dataclasses(推荐,Python 3.7+)
dataclasses是Python标准库专门用来创建数据类的工具,能帮你快速定义和初始化对应JSON结构的类,代码简洁又易维护。
首先定义对应单个货币信息的类:
from dataclasses import dataclass from typing import Optional, List import requests @dataclass class Currency: Currency: str CurrencyLong: str MinConfirmation: int TxFee: float IsActive: bool CoinType: str BaseAddress: Optional[str] # 处理JSON里的null值,允许为None
接下来写一个解析函数,把API返回的JSON数据转换成Currency类的实例列表:
def parse_currencies(response_json) -> List[Currency]: # 先判断请求是否成功 if not response_json.get("success"): raise ValueError(f"API请求失败: {response_json.get('message', '未知错误')}") currency_list = [] for item in response_json.get("result", []): # 直接用字典解包初始化类实例 currency = Currency(**item) currency_list.append(currency) return currency_list
然后就可以这样使用:
# 你原来的请求代码 coins = requests.get("https://bittrex.com/api/v1.1/public/getcurrencies") coins_json = coins.json() # 解析为类实例列表 currencies = parse_currencies(coins_json) # 示例:访问第一个货币的信息 print(currencies[0].Currency) # 输出 "BTC" print(currencies[0].TxFee) # 输出 0.00020000
方案2:使用普通类(兼容Python 3.6及以下)
如果你的Python版本不支持dataclasses,可以用普通类加构造函数来实现:
class Currency: def __init__(self, Currency, CurrencyLong, MinConfirmation, TxFee, IsActive, CoinType, BaseAddress=None): self.Currency = Currency self.CurrencyLong = CurrencyLong self.MinConfirmation = MinConfirmation self.TxFee = TxFee self.IsActive = IsActive self.CoinType = CoinType self.BaseAddress = BaseAddress # 默认设为None,对应JSON的null # 解析函数和上面类似,只是初始化方式改成普通构造 def parse_currencies(response_json): if not response_json.get("success"): raise ValueError(f"API请求失败: {response_json.get('message', '未知错误')}") currency_list = [] for item in response_json.get("result", []): currency = Currency( Currency=item["Currency"], CurrencyLong=item["CurrencyLong"], MinConfirmation=item["MinConfirmation"], TxFee=item["TxFee"], IsActive=item["IsActive"], CoinType=item["CoinType"], BaseAddress=item.get("BaseAddress") # 用get避免键不存在的问题 ) currency_list.append(currency) return currency_list
小提示
- 处理API返回的数据时,一定要先检查
success字段是否为true,避免处理错误的响应数据 - 用
Optional类型(或者在普通类里设默认值为None)来处理JSON中的null值,避免报错 - 类的字段名我直接用了JSON里的键名,如果你觉得不符合Python的下划线命名法(比如想改成
currency_long),也可以在初始化的时候做映射,比如self.currency_long = item["CurrencyLong"]
内容的提问来源于stack exchange,提问作者Deadmon
相关产品推荐
相关产品推荐

