AttributeError:' list'对象没有属性' get'?

时间:2018-04-01 05:19:14

标签: json python-3.x

这是脚本

def validate_record_schema(record):
        device = record.get('Payload', {})
        manual_added= device.get('ManualAdded', None)
        location = device.get('Location', None)
        if isinstance(manual_added, dict) and isinstance(location, dict):
            if 'Value' in manual_added and 'Value' in location:
                return False
        return isinstance(manual_added, bool) and isinstance(location, str)

    print([validate_record_schema(r) for r in data])

这是json数据

data = [{
        "Id": "12",
        "Type": "DevicePropertyChangedEvent",
        "Payload": [{
            "DeviceType": "producttype",
            "DeviceId": 2,
            "IsFast": false,
            "Payload": {
                "DeviceInstanceId": 2,
                "IsResetNeeded": false,
                "ProductType": "product",
                "Product": {
                    "Family": "home"
                },
                "Device": {
                    "DeviceFirmwareUpdate": {
                        "DeviceUpdateStatus": null,
                        "DeviceUpdateInProgress": null,
                        "DeviceUpdateProgress": null,
                        "LastDeviceUpdateId": null
                    },
                    "ManualAdded": {
                    "value":false
                    },
                    "Name": {
                        "Value": "Jigital60asew",
                        "IsUnique": true
                    },
                    "State": null,
                    "Location": {
                    "value":"bangalore"
                   },
                    "Serial": null,
                    "Version": "2.0.1.100"
                }
            }
        }]
    }]

对于第device = device.get('ManualAdded', None)行,我收到以下错误:AttributeError: 'list' object has no attribute 'get'.

请看一下并帮我解决这个问题

我在做错的地方......

如何解决此错误?

请帮我解决这个问题

2 个答案:

答案 0 :(得分:2)

在遍历data时跟踪类型时遇到问题。一个技巧是沿途添加打印件以进行调试,以查看发生了什么。例如,顶部的“Payload”对象是dict的列表,而不是单个dict。该列表暗示您可以拥有多个设备描述符,因此我编写了一个检查所有设备描述符的示例,如果在此过程中发现错误则返回False。您可能需要根据验证规则对此进行更新,但这将帮助您入门。

def validate_record_schema(record):
    """Validate that the 0 or more Payload dicts in record
    use proper types"""
    err_path = "root"
    try:
        for device in record.get('Payload', []):
            payload = device.get('Payload', None)
            if payload is None:
                # its okay to have device without payload?
                continue
            device = payload["Device"]
            if not isinstance(device["ManualAdded"]["value"], bool):
                return False
            if not isinstance(device["Location"]["value"], str):
                return False
    except KeyError as e:
        print("missing key")
        return False

    return True

答案 1 :(得分:0)

如错误所示,您不能在列表中.get()。要获取位置和手动添加字段,您可以使用:

    manual_added = record.get('Payload')[0].get('Payload').get('Device').get('ManualAdded')
    location = record.get('Payload')[0].get('Payload').get('Device').get('Location')

所以你的功能将成为:

def validate_record_schema(record):
    manual_added = record.get('Payload')[0].get('Payload').get('Device').get('ManualAdded')
    location = record.get('Payload')[0].get('Payload').get('Device').get('Location')

    if isinstance(manual_added, dict) and isinstance(location, dict):
        if 'Value' in manual_added and 'Value' in location:
        return False
    return isinstance(manual_added, bool) and isinstance(location, str)

请注意,这会将位置设置为

{
    "value":"bangalore"
}

和manual_added to

{
    "value":false
}