1

I am working on converting an API from slim / PHP to flask / Python.

I am using a JSON validator in the slim application, and in that case, all keys specified in the objects within the schema are required by default. Causing validation failures if a key is missing, unless specified as "optional".

I am installed pip install jsonschema for use in my python. By default the keys are not required unless specified as required after the object.

Is there any way to make the python "version" of this validator work like the slim "version" I was working with? This would save a ton of updating the schema's I have already defined.

user3582887
  • 403
  • 3
  • 6
  • 19

1 Answers1

1

Pandas is a great library to help with data :

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)

Outputs :

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']
Loïc
  • 11,804
  • 1
  • 31
  • 49
  • This seems to still require explicitly specifying the required fields, and maybe an extra dependency of pandas than just using the `required` field in the json-schema spec. http://json-schema.org/examples.html – danielx Nov 25 '16 at 20:54
  • yes, it's me trying pandas around, haha. Great lib though! – Loïc Nov 25 '16 at 21:41