尝试从 JSON 响应中的列表中获取值

Trying to get values form a list inside a JSON respons

我的目标是遍历 JSON 响应,获取两个值,并构建一个 API 调用以将信息加载到 POST 以创建我正在构建的策略.

首先,我尝试从 JSON 响应中获取两个值以分配为变量以构建 POST 调用,这将是此操作的第二步。由于分配了每个不同的“id”和“name”键,我想构建一个 JSON 有效负载并一次发送一个 POST 调用。键“id”和“name”在响应负载中出现多次,我在捕获这两个键时遇到问题。

JSON 回应

data =  {
 "data":[
 {
    "id":"02caf2be-3245-4d3d",
    "name":"ORA-FIN-ACTG",
    "description":"Oracle",
    "links":{
       "web":"https://com/",
       "api":"https://com/"
    }
 },
 {
    "id":"03af2f46-fad6-41a1",
    "name":"NBCMAINFRAME",
    "description":"Network",
    "links":{
       "web":"https://com/",
       "api":"https://com/"
    }
 },
 {
    "id":"0649628b-0e3b-48df",
    "name":"CAMS",
    "description":"Customer",
    "links":{
       "web":"https://com/",
       "api":"https://com/"
    }
 },
 {
    "id":"069d4bcf-3e50-4105",
    "name":"SHAREPOINTSITES",
    "description":"Sharepoint",
    "links":{
       "web":"https://com/",
       "api":"https://com/"
    }
 }
],
"took":0.013,
"requestId":"1f364470"

}

我试过各种“for循环”来抓取数据。这是下面的循环之一:

data = json.loads(data)
data[0]['data'][0]['name']
for item in range(len(data)):
print(data[item]['data'][0]['name'])

我也试过把它当作字典来读:

for data_dict in data:
for key, value in data_dict.items():
    team.append(key)
    id.append(value)

    print('name = ', team)
    print('id = ', id)

我也收到 KeyError 和 TypeError:JSON 对象必须是 str、bytes 或 bytearray,而不是 'dict'。

感谢任何帮助。

仅供参考,这是我想要用“name”和“id”值填充的负载:

data= {
    "type":"alert",
    "description":"policy",
    "enabled":"true",
    "filter":{
        "type":"match-any-condition",
        "conditions":[
            {
                "field":"extra-properties",
                "key":"alertOwner",
                "operation":"equals",
                "expectedValue":name
            }
        ]
    },
    "ignoreOriginalResponders": "true",
    "ignoreOriginalTags": "true",
    "continue": "true",
    "name": str(name) + " Policy",
    "message":"{{message}}",
    "responders":[{"type":"team","id":id}],
    "alias":"{{alias}}",
    "tags":["{{tags}}"],
    "alertDescription":"{{description}}"
    }

您提供的 JSON 响应已经是字典,因此无需为此使用 json.loads。多项目列表实际上嵌套在 data 键下。所以你可以像这样简单地遍历项目数组:

for item in data["data"]:
    print("{} : {}".format(item["id"],item["name"]))

这是输出:

02caf2be-3245-4d3d : ORA-FIN-ACTG
03af2f46-fad6-41a1 : NBCMAINFRAME
0649628b-0e3b-48df : CAMS
069d4bcf-3e50-4105 : SHAREPOINTSITE