这是我的数据:
[{'DeviceInstanceId': 1, 'IsResetNeeded': False, 'ProductType': 'testing', 'Product': {'Family': '12345',"Model": "f10","Type": "data","Vendor": "qspi"}}]
我想验证结构,类型和键的顺序是否相同,如果不是,我应该打印缺少的数据
'Product': {'Family': '12345',"Model": "f10","Type": "data","Vendor": "qspi"}
答案 0 :(得分:0)
假设这是你的json转换为python字典
ordered_dict = [{' DeviceInstanceId':1,' IsResetNeeded':False,' ProductType':' testing',' ;产品':{' Family':' 12345'," Model":" f10"," Type&#34 ;:"数据","供应商":" qspi"}}]
您可以使用ordered_dict.keys()按顺序获取所有键,因为它是字典列表,您必须获取所有项目的键并相互比较以检查所有键是否按顺序排列,我正在转换为元组元组进行比较。
tuple_of_keys = tuple([tuple(j.keys()) for j in ordered_dict])
这将为你提供键元组的元组。
现在做一组像元组一样的元组,
if len(set(tuple_of_keys)) == 1:
print("all keys are in order")
else:
print("missing data")
如果length等于1则所有键的顺序都相同
比较产品密钥中的密钥,将代码更改为
tuple_of_keys = tuple([tuple(j['Product'].keys()) for j in ordered_dict])
再次按照相同的方法
如果您想手动传递密钥顺序并检查订单是否匹配,请使用以下代码。
order_of_keys = ('Vendor', 'Model', 'Type', 'Family')
ordered_dict = [{'DeviceInstanceId': 1, 'IsResetNeeded': False,
'ProductType': 'testing', 'Product': {'Family': '12345',"Model":
"f10","Type": "data","Vendor": "qspi"}},{'DeviceInstanceId': 1,
'IsResetNeeded': False, 'ProductType': 'testing', 'Product': {'Family':
'12345',"Model": "f10","Type": "data","Vendor": "qspi"}}]
def tests(order_of_keys,ordered_dict):
tuple_of_keys = tuple([tuple(j['Product'].keys()) for j in ordered_dict])
for each_item in tuple_of_keys:
if each_item == order_of_keys:
print("all keys are in order")
else:
print("missing data")
tests(order_of_keys,ordered_dict)