There are actually two questions: if I have a dictionary (which originally came from parsing a json message) that has an optional array:
dict_with = {'name':'bob','city':'san francisco','kids': {'name': 'alice'} } dict_without = {'name':'bob','city':'san francisco' }
I would usually have code like:
if 'kids' in dict: for k in dict['kids']:
My first question is: is there a python way to combine if protection and a for loop?
Second question: my gut tells me that the best design for the original json message should always indicate the children element, just with an empty dictionary:
dict_better = {'name':'bob','city':'san francisco','kids': {} }
I cannot find any design methodology that confirms this. The json message is a status message from a web service that supports json and xml views. Since they started with xml, they did it so that the kids element was optional, which forces the construct above to check to see if the element exists before iterating over the array. I would like to know if it is better to constructively state that an element is required (only with an empty array if there are no elements).
json python design
Mark
source share