json 如何使用for循环查询API响应中的数据并将结果追加到列表中?

sbdsn5lh  于 2023-10-21  发布在  其他
关注(0)|答案(1)|浏览(120)

我从一个API请求中获取深度嵌套的数据,我需要检查最内部的数据是否等于某个字符串。
下面是response["contents"]中的一个项目示例:

{
"file-name": "Some-clients-name",
"file-number": "some-index",
"assistants": [
    {
        "name": "Some-assistants-name",
        "id": "de5c-21e4-ae01"
    },
    {
        "name": "Some-assistants-name",
        "id": "1d6d-4973-b248f"
    },
    {
        "name": "Some-assistants-name",
        "id": "bd3f-482a-gffc"
    }
],
"involved": [
    {
        "contact": {
            "name": "Some name",
            "id": 6562
        },
        "role": {
            "main-role": "client",
            "side-role": "prosecutor"
        },
        "under-involved": [
            {
                "contact": {
                    "name": "Some name",
                    "id": 424t
                },
                "role": "legal protection service"
            }
        ]
    },
    {
        "contact": {
            "name": "Some name",
            "id": 339f
        },
        "role": {
            "main-role": "opponent",
            "side-role": "defendant"
        }
    }
],
"legal areas": [
    "Contract law"
],
"clerk": {
    "name": "Some name",
    "id": "4fsd-fwe4278-b07df"
},
"keywords": [],
"status": "ACTIVE",
"reason": "coaching"

}
脚本应该循环遍历response["contents"]中的每一项,并检查是否为["under-involved"]["role"] == "legal protection service"。如果为true,则键/值对“file-number”:该项目的“some-index”应该被附加到一个空列表中。如果为false,则应该将相同的键/值对追加到另一个空列表中。
因此,该脚本应该循环遍历每个记录,并将它们分类到两个列表中,一个包含涉及法律的保护服务的记录,另一个不包含。
我尝试在这里使用try/except,因为不是每个记录都包含表示“参与不足”的数据,这导致我之前的代码崩溃。

headersAuth = {
    "Authorization": "Bearer " + refreshToken(refresh_token),
    "accept": "application/json"
}

legalservice_true = []
legalservice_false = []

for i in range(0, 10):

    url = f"https://app.labrog.de/v1/awwkten?page={i}"
    response = requests.get(url, headers=headersAuth)

    for record in response.json()["content"]:
                
         try:

             for involved in record["involved"]:

                 if involved["under-involved"]:

                     for i in range(0, 5):

                        if involved["under-involved"][i]["role"] ==   "legal protection service":
                                
                            legalservice_true.append(record)
                    

         except:
                
              legalservice_false.append(record)

这里的问题是,每条记录都可以有多个“涉及“,脚本在每个“涉及“循环之后决定是否应该将记录追加到列表中。我最终在列表中多次出现相同的记录。
response["contents"]中的每条记录在输出列表中只出现一次,并且永远不会出现在两个列表中,无论它包含多少个["under-involved"] == "legal protection service"。如果脚本在记录中找到值“法律的保护服务”,则键/值对“文件号”:该记录的“some-index”进入legalservice_true列表。否则,它应该进入legalservice_false列表。
这是所需输出的示例:

legalservice_true = [{"file-number": "334/21"}, {"file-number": "337/21"}, {"file-number": "382/21"},...]
legalservice_false = [{"file-number": "352/21"}, {"file-number": "388/22"}, {"file-number": "391/22"},...]
pb3s4cty

pb3s4cty1#

试试这个:

legalservice_true = []
legalservice_false = []

legalservice = False
for involved in contents['involved']:
    if 'under-involved' in involved:
        for under_involved in involved['under-involved']:
            if ('role' in under_involved and 
                under_involved['role'] == 'legal protection service'):
                legalservice = True
                
this = {"file-number":contents["file-number"]}
if legalservice:
    legalservice_true.append(this)
else:
    legalservice_false.append(this)

如果它不能满足您的需求,请更新您的帖子,描述它失败的方式。

相关问题