如何将Digifinex WebSocket返回信息转换为JSON格式?
问题
通过Digifinex交易所WebSocket获取行情数据,执行以下代码:
from websocket import create_connection ws = create_connection("wss://openapi.digifinex.com/ws/v1/") ws.send('{"id":12312, "method":"ticker.subscribe", "params":["ETH_USDT", "BTC_USDT"]}') print(ws.recv())
期望得到的JSON格式:
{ "error": null, "result": { "status": "success" }, "id": 12312 }
但实际收到二进制乱码:
b'x\xda\x04\xc0\xb1\r\xc4 \x0c\x85\xe1]\xfe\x9a\x06\xae\xf36\'B\x11\xc9J$?\xbbB\xec\x9eo\xb3"\xde\xc0\x9ero\xc4Ryb\x1b\xe5?K\x18\xaa9\x97\xc4i\xdc\x17\xd6\xc7\xaf\x8f\xf3\x05\x00\x00\xff\xff l\x12l'
尝试用decode('UTF-8')、decode('ascii')、decode('latin-1')解码均失败,如何转换为目标JSON格式?
解决方案
Digifinex的WebSocket返回数据采用gzip压缩,直接解码自然失败,需要先解压再解析JSON,修改代码如下:
from websocket import create_connection import gzip import json ws = create_connection("wss://openapi.digifinex.com/ws/v1/") ws.send('{"id":12312, "method":"ticker.subscribe", "params":["ETH_USDT", "BTC_USDT"]}') # 接收二进制数据并解压 compressed_data = ws.recv() decompressed_data = gzip.decompress(compressed_data).decode('utf-8') # 解析为JSON对象 result = json.loads(decompressed_data) print(result)
关键说明
- 收到的二进制数据开头的
x\xda是gzip压缩数据的特征标识,可确认数据格式 - 先通过
gzip.decompress()解压二进制数据,再用utf-8解码成字符串 - 最后用
json.loads()将字符串解析为JSON对象,即可得到期望格式的结果
内容的提问来源于stack exchange,提问作者Bitcoin Earn
相关产品推荐
相关产品推荐

