在python中从文件中删除JSON密钥

2024-09-30 14:25:33 发布

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

我有一个包含多个JSON对象的文件,如下所示:

[
  {
"fields": {
    "project": {
        "key": "GID"
    },
    "description": "",
    "documentKey": "AB-TC-678",
    "globalId": "GID-462256",
    "idb_metric": "framework.jama.infra.tagged.testcases",
    "lastActivityDate": "2017-12-19",
    "name": "Admin: Action commands",
    "sequence": "4.13.2.13.5.1.17",
    "testCaseStatus": "PASSED",
    "testCaseSteps": "FIELD_NOT_PRESENT"
   }
},
{
"fields": {
    "project": {
        "key": "GID"
    },
    "description": "",
    "documentKey": "AB-TC-679",
    "globalId": "GID-462256",
    "idb_metric": "framework.jama.infra.tagged.testcases",
    "lastActivityDate": "2017-12-19",
    "name": "Admin: Action not",
    "sequence": "4.13.2.13.5.1.18",
    "testCaseStatus": "PASSED",
    "testCaseSteps": "FIELD_NOT_PRESENT"
    }
}
]

我要做的是删除key=x的行,例如,where key=“idb_metric”。使用下面的答案/评论(谢谢!),我就快到了:

^{pr2}$

但是,如果我通过添加elif来寻找第二个键,那么只会找到/删除第一个键(在第一个if块中):

elif 'sequence' in element["fields"]:
        print("Found sequence!")
        del element['fields']['sequence']
        print(element)

如果我使用上述代码,预期结果:

[
  {
"fields": {
    "project": {
        "key": "GID"
    },
    "description": "",
    "documentKey": "AB-TC-678",
    "globalId": "GID-462256",
    "lastActivityDate": "2017-12-19",
    "name": "Admin: Action commands",
    "testCaseStatus": "PASSED",
    "testCaseSteps": "FIELD_NOT_PRESENT"
   }
},
{
"fields": {
    "project": {
        "key": "GID"
    },
    "description": "",
    "documentKey": "AB-TC-679",
    "globalId": "GID-462256",
    "lastActivityDate": "2017-12-19",
    "name": "Admin: Action not",
    "testCaseStatus": "PASSED",
    "testCaseSteps": "FIELD_NOT_PRESENT"
    }
}
]

Tags: keynameprojectfieldsabadminactiondescription
1条回答
网友
1楼 · 发布于 2024-09-30 14:25:33

正如其中一位评论者所提到的,您没有在json字典中的正确字段中建立索引。在

要修复:

with open('input.json',encoding='utf8') as in_file:
    data = json.load(in_file)
    for element in data:
        del element["fields"]["idb_metric"]

    print(element["fields"])

如果您在尝试删除该密钥之前确保该密钥存在,那么它也可以为您省去一些麻烦。这是检查是否存在的一种方法:

^{pr2}$

作为对编辑后问题的回答,请不要使用elif:

if 'idb_metric' in element["fields"]:
    print("Found idb_metric!")
    del element['fields']['idb_metric']
    print(element)

if 'sequence' in element["fields"]:
    print("Found sequence!")
    del element['fields']['sequence']
    print(element)

相关问题 更多 >