如何在JSON数组上迭代以查找具有更改键的值?

2024-04-26 14:40:53 发布

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

我试图从一个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”值?你知道吗


Tags: jsondfapplicationaction数组itemnullappid
2条回答

测试属性中是否存在键以检索不同的值:

df = []

for item in json_response["items"]:
    errors = "NA" 
    if "errors" in item["attributes"]
        errors = item["attributes"]["errors"]
    elif "RefreshFailure" in item["attributes"]:
        errors = item["attributes"]["RefreshFailure"] 

    df.append({
        'AccountName': item["accountName"],
        'Action': item["action"],
        'Application': item["application"],
        'AppID': item["attributes"]["appId"],
        'AppName': item["attributes"]["AppName"],
        'Errors': 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"]
    })

我试着模仿你的数据使代码正常工作。你知道吗

import json
from pprint import pprint


json_data = '''
{
    "items": [
        {
            "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
        },
        {
            "accountName": null,
            "action": "Disable",
            "application": "Application1",
            "attributes": {
                "appId": "7d2451684288",
                "cloudAppName": "Application1",
                "RefreshFailure": true
            },
            "contextid": null,
            "created": 1553194821098,
            "hostname": null,
            "id": "ac09ea0082",
            "info": null,
            "ipaddr": null,
            "source": "System1",
            "stack": null,
            "target": "TargetName1.",
            "trackingId": null,
            "type": null
        }
    ]
}'''
json_response = json.loads(json_data)


def capitalize(s):
    return s[0].upper() + s[1:]


df = []

for item in json_response["items"]:
    d = {}
    # Iterate over the items in the dictionary/json object and add them one by one using a loop
    # This will work even if the items in the json_response changes without having to change the code
    for key, value in item.items():
        # "attributes" is itself a dictionary/json object
        # Its items have to be unpacked and added instead of adding it as a raw object
        if isinstance(value, dict):
            for k, v in value.items():
                d[capitalize(k)] = v
        else:
            d[capitalize(key)] = value

    df.append(d)

pprint(df)

输出:

[{'AccountName': None,
  'Action': 'Disable',
  'AppId': '7d264050024',
  'AppName': 'Application1',
  'Application': 'Application1',
  'Contextid': None,
  'Created': 1553194821098,
  'Errors': ['Rule: Rule not found.'],
  'Hostname': None,
  'Id': 'ac09ea0082',
  'Info': None,
  'Ipaddr': None,
  'Source': 'System1',
  'Stack': None,
  'Target': 'TargetName1.',
  'TrackingId': None,
  'Type': None},
 {'AccountName': None,
  'Action': 'Disable',
  'AppId': '7d2451684288',
  'Application': 'Application1',
  'CloudAppName': 'Application1',
  'Contextid': None,
  'Created': 1553194821098,
  'Hostname': None,
  'Id': 'ac09ea0082',
  'Info': None,
  'Ipaddr': None,
  'RefreshFailure': True,
  'Source': 'System1',
  'Stack': None,
  'Target': 'TargetName1.',
  'TrackingId': None,
  'Type': None}]

如果希望键名是Errors,即使实际的键名是RefreshFailure,也可以在df.append(d)之前添加这些代码行

...
if 'RefreshFailure' in d:
    d['Errors'] = d['RefreshFailure']
    del d['RefreshFailure']

df.append(d)

有了这几行额外的代码,输出将如下所示:

[{'AccountName': None,
  'Action': 'Disable',
  'AppId': '7d264050024',
  'AppName': 'Application1',
  'Application': 'Application1',
  'Contextid': None,
  'Created': 1553194821098,
  'Errors': ['Rule: Rule not found.'],
  'Hostname': None,
  'Id': 'ac09ea0082',
  'Info': None,
  'Ipaddr': None,
  'Source': 'System1',
  'Stack': None,
  'Target': 'TargetName1.',
  'TrackingId': None,
  'Type': None},
 {'AccountName': None,
  'Action': 'Disable',
  'AppId': '7d2451684288',
  'Application': 'Application1',
  'CloudAppName': 'Application1',
  'Contextid': None,
  'Created': 1553194821098,
  'Errors': True,
  'Hostname': None,
  'Id': 'ac09ea0082',
  'Info': None,
  'Ipaddr': None,
  'Source': 'System1',
  'Stack': None,
  'Target': 'TargetName1.',
  'TrackingId': None,
  'Type': None}]

相关问题 更多 >