Python处理交易API返回JSON中的null值问题
处理交易API返回JSON中的null值问题
场景说明
用Python从网络交易API获取数据,返回的JSON结构如下(包含500余个类似字典的列表):
{ "result": [ { "name": "ALGOBEAR/USD", "enabled": true, "postOnly": false, "priceIncrement": 1e-08, "sizeIncrement": 1000000000000.0, "minProvideSize": 1000000000000.0, "last": 1e-08, "bid": null, "ask": null, "price": null, "type": "spot", "futureType": null, "baseCurrency": "ALGOBEAR", "isEtfMarket": true, "quoteCurrency": "USD", "underlying": null, "restricted": false, "highLeverageFeeExempt": true, "largeOrderThreshold": 350.0, "change1h": 0.0, "change24h": 0.0, "changeBod": 0.0, "quoteVolume24h": 0.0, "volumeUsd24h": 0.0, "priceHigh24h": 0.0, "priceLow24h": 0.0 }]}
遇到的问题:JSON中的null值(如"price": null)无法与其他字典的float类型价格值(如"price": 0.00019845)直接进行大小、相等比较,导致程序报错。
解决方案
方案1:将JSON的null转为Python的None处理
Python标准库的json模块默认会把JSON中的null解析为Python的None,无需额外配置。你可以在后续逻辑中判断None值,避免比较报错:
基础解析与判断
import json # 假设api_response是API返回的原始字符串 api_response = "..." # 替换为你的API响应数据 data = json.loads(api_response) trading_pairs = data["result"] # 遍历处理,跳过或处理price为None的条目 for pair in trading_pairs: current_price = pair.get("price") if current_price is not None: # 正常执行比较逻辑 if current_price > 0.0001: print(f"{pair['name']} 价格达标: {current_price}")
替换None为默认值(如0.0)
如果需要统一数据类型,可以把None替换为指定默认值:
processed_pairs = [] for pair in trading_pairs: cleaned_pair = pair.copy() # 对需要处理的字段替换None for key in ["price", "bid", "ask"]: if cleaned_pair[key] is None: cleaned_pair[key] = 0.0 processed_pairs.append(cleaned_pair)
方案2:直接过滤含null值的字典
如果不需要保留含null的条目,可以直接过滤:
过滤特定字段(如price)为null的字典
# 只保留price不为None的交易对 filtered_pairs = [pair for pair in trading_pairs if pair.get("price") is not None]
过滤任何字段含null的字典
如果要移除所有存在None值的字典:
filtered_pairs = [] for pair in trading_pairs: # 检查字典中是否有值为None has_null_value = any(val is None for val in pair.values()) if not has_null_value: filtered_pairs.append(pair)
内容的提问来源于stack exchange,提问作者useeeeer132
相关产品推荐
相关产品推荐

