首页 > 解决方案 > 在 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 时会出现解析错误...为什么需要将其转换回字符串,因为我需要它作为对象/整数以供以后使用?

标签: pythonjsonpython-asyncio

解决方案


推荐阅读