I am attemping to traverse a JSON object where I am trying to build a simple rule:
If dict item has a key called 'breakup'
, iterate over each item in the value of that item till the time there are no more values in 'breakup'
and return a dictionary which contains two items 'name'
and 'amount'
which will be then appended into a list of dictionaries containing all the charges.
For Example:
[{'name': 'Brokerage', 'amount': 0.0}, {'name': 'Exchange Transaction Charges', 'amount': 0.3864}, {'name': 'Stamp Duty', 'amount': 1.8}, {'name': 'Regulatory Fees', 'amount': 0.012},{'name': 'Security Transaction Tax', 'amount': 12.0}, {'name': 'GST', 'amount': 0.071756}]
Sample Starting data:
my_dict = {'total_charges': 14.270156, 'trade_value': 12000, 'breakup': [{'name': 'Brokerage', 'amount': 0.0, 'msg': '', 'breakup': []}, {'name': 'External Charges', 'amount': 2.1984, 'msg': '', 'breakup': [{'name': 'Exchange Transaction Charges', 'amount': 0.3864, 'msg': '', 'breakup': []}, {'name': 'Stamp Duty', 'amount': 1.8, 'msg': '', 'breakup': []}, {'name': 'Regulatory Fees', 'amount': 0.012, 'msg': '', 'breakup': []}]}, {'name': 'Taxes', 'amount': 12.071756, 'msg': '', 'breakup': [{'name': 'Security Transaction Tax', 'amount': 12.0, 'msg': '', 'breakup': []}, {'name': 'GST', 'amount': 0.071756, 'msg': '', 'breakup': []}]}]}
I understand that this will need to be a recursive function. What I have come up with so far is:
def my_filtering_function(pair):
filter_keys = ['name', 'amount']
key, value = pair
if key in filter_keys:
return True # keep pair in the filtered dictionary
else:
return False # filter pair out of the dictionary
def json_traverse(json_object):
charges_list = []
if "breakup" in json_object and len(json_object['breakup']) == 0:
charges_list.append(dict(filter(my_filtering_function, a.items())))
else:
breakup = json_object['breakup']
for item in breakup:
json_traverse(item)
I have tried multiple other variations but none seem to be working. Any suggestions would be quite helpful.