我有一个包含多个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"
}
}
]
正如其中一位评论者所提到的,您没有在json字典中的正确字段中建立索引。在
要修复:
如果您在尝试删除该密钥之前确保该密钥存在,那么它也可以为您省去一些麻烦。这是检查是否存在的一种方法:
^{pr2}$作为对编辑后问题的回答,请不要使用elif:
相关问题 更多 >
编程相关推荐