在python 3.8中无法达到嵌套的JSON。

问题描述 投票:0回答:1

正在处理一个来自Websockets订阅的响应。

响应的内容是这样的。

{'jsonrpc': '2.0', 'method': 'subscription', 'params': {'channel': 'book.BTC-PERPETUAL.none.1.100ms', 'data': {'timestamp': 1588975154127, 'instrument_name': 'BTC-PERPETUAL', 'change_id': 19078703948, 'bids': [[10019.5, 8530.0]], 'asks': [[10020.0, 506290.0]]}}}

我试图到达第一个也是唯一的一个值在 "bids""asks" 数组通过 json.loads()

代码是这样的。

   async def __async__get_ticks(self):
  async with self.ws as echo:
     await echo.send(json.dumps(self.request))
     while True:
            response = await echo.receive()
            responseJson = json.loads(response)
            print(responseJson["params"]["data"])

然后错误的说:"KeyError: 'params'

print(responseJson["params"]["data"])

KeyError: 'params'

然而我试了一下,它不想捕捉任何一个JSON后的。"jsonprc",它成功地返回了 2.0. 超出这个范围就会出现错误。

我试过用 .get(),有助于更深一层,但还是不能更多。

有什么想法,如何正确的格式化,并达到? bidsasks ?

先谢谢你。

python json websocket syntax
1个回答
1
投票

我建议使用 dict.get() 方法,但要确保当你查询那些预期有嵌套字典的字典时,将它设置为返回一个空字典。

默认情况下(如果你没有指定第二个参数给 dict.get()),它将返回 None. 这就解释了为什么你只能深入一层。

这里有一个例子。

empty_dict = {}
two_level_dict = {
    "one": {
        "level": "deeper!"
    }
}

# This will return None and the second get call will not fail, because
# the first get returned an empty dict for the .get("level") call to succeed. 
first_get = empty_dict.get("one", {}).get("level")

# This will return 'deeper!'
second_get = two_level_dict.get("one", {}).get("level")

print(first_get)
print(second_get)
© www.soinside.com 2019 - 2024. All rights reserved.