简体   繁体   English

无法到达 python 3.8 中的嵌套 JSON

[英]Can't reach nested JSON in python 3.8

Working with a response from a Websockets subscription.处理来自 Websockets 订阅的响应。

The response reads like this:响应内容如下:

{'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]]}}}

And I'm trying to reach the first and only values inside "bids" and "asks" arrays via json.loads()我试图通过json.loads()达到"bids""asks" arrays

Code looks like this:代码如下所示:

   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"])

And error says:错误说:

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

KeyError: 'params'键错误:'参数'

However I try, it doesn't want to catch any of the JSON after "jsonprc" , for which it successfully returns 2.0 .但是我尝试,它不想在"jsonprc"之后捕获任何 JSON ,它成功返回2.0 Anything beyond that always comes up with an error.除此之外的任何事情都会出现错误。

I tried using .get() , and it helps to go one level deeper, but still not more.我尝试使用.get() ,它有助于 go 更深一层,但仍然没有更多。

Any ideas on how to format this properly and reach the bids and asks ?关于如何正确格式化并达到bidsasks的任何想法?

Thank you in advance.先感谢您。

I would suggest using the dict.get() method, but make sure that you set it to return an empty dictionary when querying dictionaries that are expected to have nested dicts.我建议使用dict.get()方法,但请确保在查询预期具有嵌套字典的字典时将其设置为返回空字典。

By default (if you don't specify a second argument to dict.get() ), it will return None .默认情况下(如果您没有为dict.get()指定第二个参数),它将返回None This explains why you were only able to go one level deep.这就解释了为什么你只能 go 一层深。

Here's an example:这是一个例子:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM