简体   繁体   中英

How to verify the structure of json?

This is my data :

[{'DeviceInstanceId': 1, 'IsResetNeeded': False, 'ProductType': 'testing', 'Product': {'Family': '12345',"Model": "f10","Type": "data","Vendor": "qspi"}}]

I want to verify structure, type and keys are in same order like below or not, if not i should print missing data

'Product': {'Family': '12345',"Model": "f10","Type": "data","Vendor": "qspi"}

Assume this is your json converted to python dictionary

ordered_dict = [{'DeviceInstanceId': 1, 'IsResetNeeded': False, 'ProductType': 'testing', 'Product': {'Family': '12345',"Model": "f10","Type": "data","Vendor": "qspi"}}]

you can get all the keys in order using ordered_dict.keys(), now since it is a list of dictionary, you have to get keys of all items and compare it with each other to check if all keys are in order, i am converting to tuple of tuples to compare.

tuple_of_keys = tuple([tuple(j.keys()) for j in ordered_dict])

this will give you tuple of tuple of keys.

now do set of tuples like,

if len(set(tuple_of_keys)) == 1:
    print("all keys are in order")
else:
    print("missing data")

if length is equal to 1 then all keys are in the same order

to compare keys inside Product key, change code to

tuple_of_keys = tuple([tuple(j['Product'].keys()) for j in ordered_dict])

and follow same method again

if you want to pass order of keys manually and check if the order is matching then use below code.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM