这是脚本
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])
Run Code Online (Sandbox Code Playgroud)
这是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"
}
}
}]
}]
Run Code Online (Sandbox Code Playgroud)
对于该行device = device.get('ManualAdded', None),我收到以下错误:AttributeError: 'list' object has no attribute 'get'.
请看一下并帮助我解决这个问题
我哪里做错了...
我该如何修复这个错误?
请帮我解决这个问题
正如错误所示,您不能.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')
Run Code Online (Sandbox Code Playgroud)
所以你的函数将变成:
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)
Run Code Online (Sandbox Code Playgroud)
请注意,这会将位置设置为
{
"value":"bangalore"
}
Run Code Online (Sandbox Code Playgroud)
并手动添加到
{
"value":false
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
78438 次 |
| 最近记录: |