我怎么能通过循环传递元组?

时间:2018-04-02 14:05:49

标签: python json python-3.x isinstance

我的代码:

def validate_record_schema():
    """Validate that the 0 or more Payload dicts in record
    use proper types"""
    err_path = "root"
    try:
        for record in test1:
            for device in record.get('Payload', []):
                payload = device.get('Payload', None)
                if payload is None:
                    continue
                device = payload["Device"]
                key_data = ((device["ManualAdded"],bool), (device["Location"],str))

                for i in key_data:
                        if not isinstance(i):
                            return False

    except KeyError as err_path:
        print("missing key")
        return False
    return True

print(validate_record_schema())

我想像下面这样做,但我无法做到。

key_data = ((device["ManualAdded"],bool), (device["Location"],str))

                for i in key_data:
                        if not isinstance(i):
                            return False

如果我在下面这样做,那就是

if not isinstance((device["ManualAdded"],bool)):
   return False

但我需要像上面那样做。我怎么能这样做?

Json数据

test1 = [{'Id': '12', 'Type': 'DevicePropertyChangedEvent', 'Payload': [{'DeviceType': 'producttype', 'DeviceId': 2, 'IsFast': False, 'Payload': {'DeviceInstanceId': 2, 'IsResetNeeded': False, 'ProductType': 'product'
, 'Product': {'Family': 'home'}, 'Device': {'DeviceFirmwareUpdate': {'DeviceUpdateStatus': None, 'DeviceUpdateInProgress': None, 'DeviceUpdateProgress': None, 'LastDeviceUpdateId': None}, 'ManualAdded': False,
 'Name': {'Value': 'Jigital60asew', 'IsUnique': True}, 'State': None, 'Location': "dg", 'Serial': None, 'Version': '2.0.1.100'}}}]}]

1 个答案:

答案 0 :(得分:0)

您可以使用*运算符展开元组并将其成员作为单个参数传递。

key_data = (('This is a string', str), ('This is a string', bool))

for i in key_data:
    if isinstance(*i):
        print("yes")
    else:
        print("no")