Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用python在JSON中进行深层断言_Python_Json_Assert_Assertion - Fatal编程技术网

如何使用python在JSON中进行深层断言

如何使用python在JSON中进行深层断言,python,json,assert,assertion,Python,Json,Assert,Assertion,我正在触发一个API调用,服务器响应是JSON格式的。 响应如下所示: { "status": 0, "not_passed": 1, "why": [ { "code": 229, "reason": "some reason", } ] } 我需要断言两件事。 现状与原因 我正在使用的fro状态: r = requests.get_simple(url=Server.MY_SERVER, params=p) data = j

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

{
"status": 0, 
"not_passed": 1, 
"why": [
    {
        "code": 229, 
        "reason": "some reason", 
     }
]
}
我需要断言两件事。 现状与原因 我正在使用的fro状态:

    r = requests.get_simple(url=Server.MY_SERVER, params=p)
data = json.loads(r.content)
assert data["status"] == 0
但它不适用于“原因”,可能是因为“原因”在嵌套结构中更深。我该怎么修这个

assert data['why'][0]['reason'] == 'something'

当然,这假设
数据['why']
存在,是一个列表,包含一个dict作为其第一个元素。

向我们显示您试图访问“reason”的代码,并显示它产生的错误(如果有错误)。因此,如果元素是第二个元素,我将0改为1?