python - 在 Python 中给出错误的键
问题描述
我正在尝试从我的代码输出中获取“last_price”。我的代码是:
import asyncio
import websockets
import json
#subscribe to channel
msg3 = \
{"jsonrpc": "2.0",
"method": "public/subscribe",
"id": 42,
"params": {
"channels": ["ticker.BTC-PERPETUAL.raw"]}
}
async def call_api3(msg3):
async with websockets.connect('wss://testapp.deribit.com/ws/api/v2') as websocket:
await websocket.send(msg3)
while websocket.open:
response = await websocket.recv()
# do something with the notifications...
o = json.loads(response)
print(o['params']['data']['last_price'])
loop = asyncio.get_event_loop()
try:
asyncio.ensure_future(call_api3(json.dumps(msg3)))
loop.run_forever()
except KeyboardInterrupt:
pass
finally:
print('closing loop')
loop.close()
我的代码输出是:
{'jsonrpc': '2.0', 'method': 'subscription', 'params': {'channel': 'ticker.BTC-PERPETUAL.raw', 'data': {'timestamp': 1574491157294, 'stats': {'volume': 873649.05224518, 'low': 6777.0, 'high': 7713.0}, 'state': 'open', 'settlement_price': 7538.95, 'open_interest': 483060328, 'min_price': 7196.97, 'max_price': 7269.3, 'mark_price': 7232.85, 'last_price': 7231.0, 'instrument_name': 'BTC-PERPETUAL',
'index_price': 7234.32, 'funding_8h': -3.366e-05, 'current_funding': 0.0, 'best_bid_price': 7231.0, 'best_bid_amount': 269720.0, 'best_ask_price': 7231.5, 'best_ask_amount': 2490.0}}}
然而,当我只过滤到 ['params'] 时,我得到一个关键错误,实际上唯一对我有用的关键是 ['jsonrpc']。
我还想知道为什么我的代码在删除 json.dumps 时会出现解析错误...为什么需要将其转换回字符串,因为我需要它作为对象/整数以供以后使用?
解决方案
推荐阅读
- python - 在python中使用树状结构
- r - 如何在 R 中拟合 Conway-Maxwell-Poisson 回归?
- php - PHP/MySQL:取消选中数据所有复选框时保存数据时出错
- python - 使用 python 3 为文件属性添加版权
- html - 如何阻止水平边界相互重叠?
- pygame - TypeError:参数 1 必须是 pygame.Surface,而不是 builtin_function_or_method,get_rec 错误
- filepond - 尝试在每个文件池项目的基础上禁用删除
- reactjs - 缩小和悬停点时 Highchart 抛出错误
- c# - 为什么 Visual Studio 2019 删除了对新 .razor 文件的监视?
- c++ - 由于非 NULL 指针,使用 m_pRenderTarget 和 winapi 读取访问冲突