python - 如何引用 websocket 数据数组 python-binance
问题描述
我有一个脚本,它通过 websocket 接收这个 binance json 数据数组并通过回调函数打印到控制台:
{"e":"outboundAccountPosition","E":1600502318390,"u":1600502318389,"B":[{"a":"BTC","f":"0.00000000","l":"0.00000000"},{"a":"BNB","f":"0.00000000","l":"0.00000000"},{"a":"XTZ","f":"0.00000000","l":"0.00000000"}]}
我需要能够在回调函数中引用 BNB 余额 ["B"]["f"]。我试过这样的代码但不起作用。
def callback_function(msg)
if msg['e'] == 'outboundAccountPosition':
print(msg["B"]["f"])
打印整条消息效果很好,所以我认为我引用了数据数组错误。怎么修?谢谢
解决方案
您刚刚收到一个包含 JSON 结构的字符串。可以将其转换为 python dict。
您可以为此使用每个 JSON 库,最快的是 ujson:
import ujson as json
stream_data_dict = json.loads(stream_data_json)
print(stream_data_dict["B"]["f"])
unicorn_fy 是一个为您执行此操作并形成名称良好的 dicts 的库:https ://github.com/oliver-zehentleitner/unicorn_fy
from unicorn_fy.unicorn_fy import UnicornFy
received_stream_data_json = {"stream": "btcusdt@trade",
"data": {"e": "trade",
"E": 1556876873656,
"s": "BTCUSDT",
"t": 117727701,
"p": "5786.76000000",
"q": "0.03200500",
"b": 341831847,
"a": 341831876,
"T": 1556876873648,
"m": True,
"M": True}}
unicorn_fied_stream_data = UnicornFy.binance_com_websocket(received_stream_data_json)
print(unicorn_fied_stream_data)
>>>
{'stream_type': 'btcusdt@trade', 'event_type': 'trade', 'event_time': 1556876873656, 'symbol': 'BTCUSDT', 'trade_id': 117727701, 'price': '5786.76000000', 'quantity': '0.03200500', 'buyer_order_id': 341831847, 'seller_order_id': 341831876, 'trade_time': 1556876873648, 'is_market_maker': True, 'ignore': True, 'unicorn_fied': ['binance', '0.1.0']}
推荐阅读
- reactjs - 如何在 react.js 中使用 onClick 渲染特定组件?
- flutter - 有没有办法可以使用 arcore_flutter_plugin 嵌入虚拟现实场景
- python - for 循环没有读取我的 csv 文件中的所有行
- reactjs - 使用 react-router-dom 反应 js 页面重新加载 404 错误
- java - 在 MacO 上安装 Cassandra 时面临的问题
- haskell - 是什么让 Bytestring 变得“懒惰”?
- css - 为什么我的字体在网络上看起来与在 ttf/woff 文件中不同?
- php - php foreach 循环仅给出数组中的 1 个结果
- php - 查询格式化帮助(PHP、MySQL)遗留代码
- python - 训练图像时出现 cv2.error(重载解析失败)