【问题标题】:AttributeError: 'list' object has no attribute 'get'?AttributeError:'list' 对象没有属性'get'?
【发布时间】:2018-04-01 05:19:14
【问题描述】:

这是脚本

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'.

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

我在哪里做错了......

我该如何解决这个错误?

请帮我解决这个问题

【问题讨论】:

  • 查看数据结构,"Payload": [...] 是一个字典列表。
  • @tdelaney 我该如何解决这个问题?请帮助我
  • 你已经有了问题的答案......我只是添加了原因。它是一个列表,因此您需要处理列表中的项目。您可以按照下面的建议获取第一个元素,或者将整个内容放在 for 循环中以处理所有 dicts。
  • 我是 python 新手...你能修改我的函数吗?请...我不知道该怎么做

标签: json python-3.x


【解决方案1】:

您在遍历data 时遇到了跟踪类型的问题。一个技巧是在调试过程中添加打印以查看发生了什么。例如,顶部的“有效负载”对象是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

【讨论】:

  • 感谢您的大力帮助...我被困两天...非常感谢您
【解决方案2】:

正如错误提示的那样,您不能在列表中使用.get()。要获取 Location 和 ManualAdded 字段,您可以使用:

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"
}

手动添加到

{
    "value":false
}

【讨论】:

  • 能否在同一个函数中修改
  • 我已经扩展了答案,包括你函数中的上下文。
  • 感谢您的宝贵帮助...我被困两天...非常感谢您
  • 现在我得到 'str' 对象没有属性 'get'
  • @AnonymousUser 我建议创建一个包含更多详细信息的新问题
猜你喜欢
  • 2014-09-08
  • 1970-01-01
  • 1970-01-01
  • 2020-05-15
  • 1970-01-01
  • 2023-04-09
  • 2016-01-30
  • 2020-12-15
  • 2016-04-15
相关资源
最近更新 更多