我试图从一个JSON数组中提取许多值,因此我对它进行迭代,以便根据它们的键来提取值,但是其中一个键会根据项目的不同而变化,当循环遇到不同的键时,我会得到一个KeyError。你知道吗
我已经尝试使用try和except来捕获这个,但是由于我在整个数组中循环,所以这次它会对另一个键抛出相同的异常。你知道吗
以下是我提取值的代码:
df = []
for item in json_response["items"]:
df.append({
'AccountName': item["accountName"],
'Action': item["action"],
'Application': item["application"],
'AppID': item["attributes"]["appId"],
'AppName': item["attributes"]["AppName"],
'Errors': item["attributes"]["errors"],
'ContextID': item["contextid"],
'Created': item["created"],
'HostName': item["hostname"],
'EventID': item["id"],
'Info': item["info"],
'ipaddr': item["ipaddr"],
'EventSource': item["source"],
'Stack': item["stack"],
'Target': item["target"],
'TrackingID': item["trackingId"],
'Type': item["type"]
})
下面是一个JSON示例,我从一个更大的数组中提取:
{
"accountName": null,
"action": "Disable",
"application": "Application1",
"attributes": {
"appId": "7d264050024",
"AppName": "Application1",
"errors": [
"Rule: Rule not found."
]
},
"contextid": null,
"created": 1553194821098,
"hostname": null,
"id": "ac09ea0082",
"info": null,
"ipaddr": null,
"source": "System1",
"stack": null,
"target": "TargetName1.",
"trackingId": null,
"type": null
}
这是可行的,但有时“属性”看起来像:
"attributes": {
"appId": "7d2451684288",
"cloudAppName": "Application1",
"RefreshFailure": true
}
迭代整个数组时,如何提取“errors”值或“RefreshFailure”值?你知道吗
测试属性中是否存在键以检索不同的值:
我试着模仿你的数据使代码正常工作。你知道吗
输出:
如果希望键名是
Errors
,即使实际的键名是RefreshFailure
,也可以在df.append(d)
之前添加这些代码行有了这几行额外的代码,输出将如下所示:
相关问题 更多 >
编程相关推荐