比较json文件中列表中的元素

2024-10-01 17:32:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个场景,尝试将列表元素与json文件进行比较,如果存在匹配项,则返回某些值并创建json响应。 这是我的json数据

[
 {
    "evi": 1223,
    "evn": "testapp1",
    "conf": {
        "c_gr": "tot",
        "c_id": "112"
    }
 },
 {
    "evi": 6759,
    "evn": "testapp2",
    "conf": {
        "c_gr": "tot",
        "c_id": "112"
    }
 },
  {
    "evi": 3352,
    "evn": "testapp3",
    "conf": {
        "c_gr": "tot7",
        "c_id": "112"
    }
 }
]

以下是我迄今为止所尝试的:

response=requests.post('https://testaapp.com', headers=headers, data=data)
resp_json=response.json()
if response.status_code == 200:
    print ('working fine...!!')
else:
    print ('notworking !!')
metadata=resp_json['data']
m_list=[1123, 123445, 61887, 3352, 35811488976]
final_lst_data1 = []
final_lst_data2 = []
for key in m_list:
    temp1= key
    for keya in metadata:
        if temp1 in metadata[keya]['evi']:
           final_lst_data1.append(metadata['evn']) #return the names
           final_lst_data2.append(metadata['evn'], metadata['conf']) #return evn and conf values after checking and then dump it to json from list in same json format if not possible then convert to json from list, not sure how to do this here.

但这不起作用,因为它给了我下面的错误

    if key in metadata[keya]['evi']:
TypeError: list indices must be integers or slices, not dict

Tags: keyinidjsondataifresponseconf
1条回答
网友
1楼 · 发布于 2024-10-01 17:32:06

您正在使用字典作为索引。当您说“for keya in metadata:”时,keya是一个字典,它引用了“metadata”中的字典列表。因此,您不需要使用元数据[keya]来访问每个元素,只需使用“keya”

for keya in metadata:
    if temp1 == keya['evi']:
       final_lst_data1.append(keya['evn'])
       final_lst_data2.append([keya['evn'], keya['conf']])

相关问题 更多 >

    热门问题