我正在嘗試從 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}
但是,我只想使用“資料”字串中的一些資料,例如“last_price”和“timestamp_e6”。我通過嘗試拆分輸出字串來嘗試此操作,但目前沒有任何運氣。
任何幫助將不勝感激。謝謝
uj5u.com熱心網友回復:
收到的字串ws.recv()是 JSON 格式。可以通過執行以下操作將此字串轉換為字典:
import json
bybitresult = json.loads(ws.recv())
從那里,您可以像使用字典一樣從中獲取任何資料。
Python 中的 JSON
uj5u.com熱心網友回復:
將字串轉成字典,可以通過json包來實作,這樣我們就可以通過參考keys來獲取值??。
import json
dict_Bybitresult = json.loads(Bybitresult)
last_price = dict_Bybitresult['data']['last_price']
timestamp_e6 = dict_Bybitresult['timestamp_e6']
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520241.html
上一篇:更改串列中字串的某些索引值
下一篇:從串列中的日期字串中提取日期
