Python中解析JSON字符串并获取最新bid类型价格的方法求助
嘿,别慌!作为Python新手碰到这种JSON解析的问题太正常了,我来帮你一步步搞定~
解决方法:获取最新Bid价格
我们需要分三步完成:正确解析JSON、筛选Bid类型条目、找出时间戳最新的价格。
1. 先正确解析JSON数据
你之前的代码问题在于没搞清楚JSON的结构——解析后的字典顶层键是dollar_pound,对应的才是包含所有交易记录的列表,不是直接能拿到price的。先看怎么正确加载:
import json # 如果是从请求获取数据,就用json.loads(request.text) # 这里先拿你的示例数据演示 json_str = '{"dollar_pound":[{"type":"ask","price":0.01769341,"amount":1.10113151,"tid":200019988,"timestamp":1515919171},{"type":"ask","price":0.017755,"amount":3.95681783,"tid":200019987,"timestamp":1515919154},{"type":"bid","price":0.01778859,"amount":3.7753814,"tid":200019986,"timestamp":1515919152},{"type":"ask","price":0.017755,"amount":0.01216145,"tid":200019985,"timestamp":1515919147},{"type":"ask","price":0.017755,"amount":0.05679142,"tid":200019984,"timestamp":1515919135}]}' parsed_json = json.loads(json_str)
2. 筛选出所有Type为'bid'的条目
用列表推导式把符合条件的记录挑出来,这样就不用管那些'ask'类型的了:
bid_records = [record for record in parsed_json['dollar_pound'] if record['type'] == 'bid']
3. 找出Timestamp最新的价格
用max()函数,指定按timestamp字段排序,就能直接拿到最新的那条记录,再提取它的price就行。记得先判断有没有bid记录,避免空列表报错:
if bid_records: latest_bid = max(bid_records, key=lambda x: x['timestamp']) latest_bid_price = latest_bid['price'] print(f"最新的Bid价格是:{latest_bid_price}") else: print("没有找到任何Bid类型的交易记录哦")
完整可运行代码
把上面的步骤整合起来,直接就能跑:
import json # 替换成你的实际数据来源(比如request.text) json_data = '{"dollar_pound":[{"type":"ask","price":0.01769341,"amount":1.10113151,"tid":200019988,"timestamp":1515919171},{"type":"ask","price":0.017755,"amount":3.95681783,"tid":200019987,"timestamp":1515919154},{"type":"bid","price":0.01778859,"amount":3.7753814,"tid":200019986,"timestamp":1515919152},{"type":"ask","price":0.017755,"amount":0.01216145,"tid":200019985,"timestamp":1515919147},{"type":"ask","price":0.017755,"amount":0.05679142,"tid":200019984,"timestamp":1515919135}]}' # 解析JSON parsed_data = json.loads(json_data) # 筛选Bid记录 bid_items = [item for item in parsed_data['dollar_pound'] if item['type'] == 'bid'] # 获取最新Bid价格 if bid_items: latest_bid = max(bid_items, key=lambda item: item['timestamp']) print(f"最新的Bid价格:{latest_bid['price']}") else: print("未找到任何Bid类型的交易记录")
为啥你的之前代码无效?
你写的price = parsed_json['price'][0]有两个问题:
- 解析后的字典里根本没有
price这个顶层键,得先进入parsed_json['dollar_pound']这个列表 - 就算拿到列表,直接取第一个元素的价格,既不能保证是Bid类型,也不能保证是最新的,所以必须先筛选再找最大值
内容的提问来源于stack exchange,提问作者Faiz Ali
相关产品推荐
相关产品推荐

