Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.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列表中的嵌套json时出错_Python_Json_List - Fatal编程技术网

在python中访问json列表中的嵌套json时出错

在python中访问json列表中的嵌套json时出错,python,json,list,Python,Json,List,我有一个样本json数据,它作为一个POST请求的响应而来-response是下面样本json数据变量的名称: { "statusCode": "OK", "data": [ { "id": -199, "result": { "title": "test1", "group": "test_grp2" } },

我有一个样本
json
数据,它作为一个
POST
请求的响应而来-
response
是下面样本
json
数据变量的名称:

{
    "statusCode": "OK",
    "data": [
        {
            "id": -199,
            "result": {
                "title": "test1",
                "group": "test_grp2"
            }
        },
        {
            "id": -201,
            "result": {
                "title": "test2",
                "group": "test_grp2"
            }
        }
    ]
}
现在我想做的是形成一个列表的
列表
,其中每个列表都有
id
title
,以及
值,这些值来自上面的
json
数据。下面是我的代码的样子:

def get_list():
    # code to get the response from POST request

    json_data = json.loads(response.text)
    group_list = []

    if json_data['statusCode'] == 'OK':
        for data in json_data['data']:
            print(data)
            for result_data in data['result']:  
                title = result_data['title']
                group = result_data['group']
            group_list.append([data['id'],title,group])

    return(group_list)

当我执行此操作时,我得到一个错误,因为在
title=result\u data['title]
行中,列表索引必须是int而不是str。如何形成上面的列表?

数据['result']
在您的案例中是一本字典。当您使用数据['result']中的
对结果数据进行迭代时,您会得到键-换句话说,
结果数据
是一个字符串,它不支持字符串索引

相反,你的意思是:

for data in json_data['data']:
    result_data = data['result']

    title = result_data['title']
    group = result_data['group']
或者,您也可以使用:


您可以使用列表理解直接提取列表列表:

>>> [[d['id'], d['result']['title'], d['result']['group']] for d in json_data['data']]
[[-199, 'test1', 'test_grp2'], [-201, 'test2', 'test_grp2']]
>>> [[d['id'], d['result']['title'], d['result']['group']] for d in json_data['data']]
[[-199, 'test1', 'test_grp2'], [-201, 'test2', 'test_grp2']]