【问题标题】:compare elements from list in a json file比较json文件中列表中的元素
【发布时间】:2020-01-06 10:09:37
【问题描述】:

我有一个场景,我试图将列表元素与 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

【问题讨论】:

  • @Nathan 试过 for keya in range(len(metadata)) 得到这个错误 TypeError: argument of type 'int' is not iterable
  • @Nathan 请在此处查看儿子的实际数据jsfiddle.net/sa9tLygk

标签: python json python-3.x python-2.7


【解决方案1】:

您正在使用字典作为索引。当您说“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']])

【讨论】:

  • 尝试了同样的方法,它在final_lst_data2.append(keya['evn'], keya['conf'])下给了我错误TypeError: append() takes exactly one argument (2 given)
  • 正如我在问题中所问的那样,如果我需要在 json 中转换 final_lst_data2 的列表响应,我该怎么做?
  • 你得到的错误是因为最后一行,你可以简单地将两个参数包含在一个列表中。
  • 对于 json,json.dumps 应该可以正常工作。这就是为什么我没有将它包含在答案中。
  • 我有像这样final_lst_data2 = [] 一样的声明列表,并像这样附加final_lst_data2.append(keya['evn'], keya['conf']) 但我仍然遇到同样的错误,你能提供答案吗?
猜你喜欢
  • 2015-09-30
  • 2023-04-03
  • 1970-01-01
  • 2020-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多