Pandas是一個偉大的圖書館,以幫助數據:
from pandas.io.json import json_normalize
req = ['p1', 'p2.p2A', 'p3'] # required parameters
rec = {'p1' : 1, 'p2' : {'p2A' : 2, 'p2B':3}, 'p3':4} # what we received
recFlat = json_normalize(rec).to_dict().keys() # flatten received parameters, and get the list of the keys
print('required: %s' % req)
print('received: %s' % rec)
print(' flat : %s' % recFlat)
req_in_rec = set(req).issubset(recFlat) # test if required parameters are in received parameters
print('required parameters set: ', req_in_rec)
req.append('p22.A') # new parameters are required
req.append('p4')
print('\nnew required parameters : %s' % req)
req_in_rec = set(req).issubset(recFlat) # test if required parameters are in received parameters
print('required parameters set: ', req_in_rec)
missing_parameters = list(req - recFlat)
print('missing parameters : %s' % missing_parameters)
輸出:
required: ['p1', 'p2.p2A', 'p3']
received: {'p2': {'p2A': 2, 'p2B': 3}, 'p3': 4, 'p1': 1}
flat : dict_keys(['p2.p2B', 'p2.p2A', 'p1', 'p3'])
required parameters set: True
new required parameters : ['p1', 'p2.p2A', 'p3', 'p22.A', 'p4']
required parameters set: False
missing parameters : ['p4', 'p22.A']
這似乎仍然需要明確地指定所需的字段,比只用大熊貓也許一個額外的依賴json-schema規範中的'required'字段。 http://json-schema.org/examples.html – danielx
是的,這是我想熊貓周圍,哈哈。儘管偉大的自由! –