gpt4 book ai didi

json - 属性错误 : 'list' object has no attribute 'get' ?

转载 作者:行者123 更新时间:2023-12-03 23:16:41 26 4
gpt4 key购买 nike

这是脚本

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'.
请看看并帮助我解决这个问题

我在哪里做错了...

我该如何解决这个错误?

请帮我解决这个问题

最佳答案

您在遍历时遇到跟踪类型的问题 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

关于json - 属性错误 : 'list' object has no attribute 'get' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49595050/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com