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

时间:2018-10-24 23:09:03

标签: python json

我有一个包含多个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处的行,例如,其中key =“ idb_metric”。使用下面的答案/评论(谢谢!),我快要到了:

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

但是,如果我通过添加一个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"
    }
}
]

1 个答案:

答案 0 :(得分:2)

正如其中一位评论者所述,您没有在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"])

如果在尝试将其删除之前确定密钥已经存在,它也可能使您省去一些麻烦。这是检查它是否存在的一种方法:

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

作为对已编辑问题的解答,请不要使用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)