You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何过滤WebSocket请求返回的ByBit API指定数据?

解决方案

别用字符串分割,直接把返回的JSON字符串解析成Python字典,就能精准提取你要的字段,这比字符串分割靠谱太多,也不容易出错。

修改后的代码如下:

import json
from websocket import create_connection

ws = create_connection("wss://stream-testnet.bybit.com/realtime")
ws.send('{"op": "subscribe", "args": ["instrument_info.100ms.BTCUSD"]}')
bybitresult = ws.recv()
# 解析JSON字符串为Python字典
result_dict = json.loads(bybitresult)
# 提取目标字段并存储到变量
last_price = result_dict["data"]["last_price"]
timestamp_e6 = result_dict["timestamp_e6"]
# 输出验证结果
print(f"最新价格: {last_price}")
print(f"微秒级时间戳: {timestamp_e6}")
ws.close()

补充说明

  • json.loads()会把JSON格式的字符串转换成字典结构,让你可以通过键名直接访问对应值,完全不用处理冗余内容
  • 要是担心API返回结构变动导致字段不存在,可以用dict.get()避免报错,示例:
    last_price = result_dict.get("data", {}).get("last_price", "无数据")
    timestamp_e6 = result_dict.get("timestamp_e6", "无数据")
    

内容的提问来源于stack exchange,提问作者james

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 08:10:31