我正在尝试过滤WebSocket请求中的信息。我可以很好地完成请求,但是返回的响应信息比我实际需要的信息多。我想过滤掉此信息,然后在变量中使用它。
例如,如果我只使用ByBit WebSocket api中的示例代码
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()
print(bybitresult)
ws.close()
我得到了下面的响应
{"topic":"instrument_info.100ms.BTCUSD","type":"snapshot","data":{"id":1,"symbol":"BTCUSD","last_price_e4":192785000,"last_price":"19278.50","bid1_price_e4":192780000,"bid1_price":"19278.00","ask1_price_e4":192785000,"ask1_price":"19278.50","last_tick_direction":"ZeroPlusTick","prev_price_24h_e4":192650000,"prev_price_24h":"19265.00","price_24h_pcnt_e6":700,"high_price_24h_e4":204470000,"high_price_24h":"20447.00","low_price_24h_e4":187415000,"low_price_24h":"18741.50","prev_price_1h_e4":192785000,"prev_price_1h":"19278.50","price_1h_pcnt_e6":0,"mark_price_e4":192886700,"mark_price":"19288.67","index_price_e4":193439800,"index_price":"19343.98","open_interest":467889481,"open_value_e8":0,"total_turnover_e8":1786988413378107,"turnover_24h_e8":65984748882,"total_volume":478565052570,"volume_24h":12839296,"funding_rate_e6":-677,"predicted_funding_rate_e6":-677,"cross_seq":5562806725,"created_at":"2018-12-29T03:04:13Z","updated_at":"2022-10-25T06:09:48Z","next_funding_time":"2022-10-25T08:00:00Z","countdown_hour":2,"funding_rate_interval":8,"settle_time_e9":0,"delisting_status":"0"},"cross_seq":5562806725,"timestamp_e6":1666678189180180}
但是,我只想使用“data”字符串中的一些数据,例如“last_price”和“timestamp_e6”。我已经尝试过拆分输出字符串,但目前没有任何运气。
如有任何帮助,我将不胜感激。谢谢
2条答案
按热度按时间ax6ht2ek1#
从
ws.recv()
接收到的字符串是JSON格式的。可以通过执行以下操作将该字符串转换为字典:从那里,你可以像使用字典一样从中获取任何数据。
JSON in Python
zed5wv102#
将字符串转换成字典,可以使用json包来实现,这样我们就可以通过引用键来获取值👇。