【问题标题】:How to assert deeply in JSON with python如何使用 python 在 JSON 中进行深度断言
【发布时间】:2016-01-27 18:56:15
【问题描述】:

我正在触发 API 调用,服务器响应是 JSON 格式。 响应如下所示:

{
"status": 0, 
"not_passed": 1, 
"why": [
    {
        "code": 229, 
        "reason": "some reason", 
     }
]
}

我需要断言两件事。 现状及原因 来自我正在使用的状态:

    r = requests.get_simple(url=Server.MY_SERVER, params=p)
data = json.loads(r.content)
assert data["status"] == 0

但它不适用于“原因”,可能是因为“原因”在嵌套结构中更深。我该如何解决这个问题?

【问题讨论】:

  • 向我们展示您尝试访问“原因”的代码,并在出现错误时显示它产生的错误。

标签: python json assert assertion


【解决方案1】:
assert data['why'][0]['reason'] == 'something'

当然,这假设data['why'] 存在,是一个列表,并且包含一个字典作为其第一个元素。

【讨论】:

  • 所以如果元素是第二个,我将 0 更改为 1?
猜你喜欢
  • 2021-12-11
  • 2019-07-11
  • 1970-01-01
  • 2017-11-08
  • 1970-01-01
  • 1970-01-01
  • 2011-09-25
  • 1970-01-01
  • 2022-11-17
相关资源
最近更新 更多