When you take JSON data, you may want to reject certain fields from the JSON structure. Here’s an algorithm to compare the source JSON and the denied fields list and return True
if there’s any field that is not allowed in the source JSON.
# Here's a function that checks if there's any not-allowed-fields are included in the source JSON data
def is_denied_field_in_json(deny={}, source={}):
for key, t_val in deny.items():
s_val = source.get(key)
if s_val is None:
continue
elif not isinstance(t_val, dict):
return True
elif isinstance(t_val, dict)\
and isinstance(s_val, dict)\
and is_denied_field_in_json(t_val, s_val):
return True
return False
# This is the JSON data a user tries insert
source = {
"a": 1,
"b": {
"bb": 2,
},
"c": 3,
"d": {
"dd": {
"ddd": {
"dddd": 4
}
}
}
}
# Here're the test deny lists you can define in your code
deny_list_true1 = {
"a": 0,
}
deny_list_true2 = {
"n": 0,
"a": 0,
}
deny_list_true3 = {
"b": {
"bb": 0
}
}
deny_list_true4 = {
"b": {
"n": 0
},
"c": 3
}
deny_list_true5 = {
"d": {
"dd": {
"ddd": 0
}
}
}
deny_list_false1 = {
"n": 0,
}
deny_list_false2 = {
"b": {
"n": 0
}
}
deny_list_false3 = {
"d": {
"n": {
"dd": {
"ddd": 0
}
}
}
}
print(is_denied_field_in_json(deny_list_true1, source))
print(is_denied_field_in_json(deny_list_true2, source))
print(is_denied_field_in_json(deny_list_true3, source))
print(is_denied_field_in_json(deny_list_true4, source))
print(is_denied_field_in_json(deny_list_true5, source))
print(is_denied_field_in_json(deny_list_false1, source))
print(is_denied_field_in_json(deny_list_false2, source))
print(is_denied_field_in_json(deny_list_false3, source))