I have a sample JSON like:
{'key1': {'key2': 2, 'key3': 1, 'key4' : 1}}
and I would like to remove each leaf node once and print the JSON using python.
For that, I have the code for printing all the leaf nodes. But, can someone help write for me the code for dynamically remove a leaf node - one at a time
def print_all_leaf_nodes(data):
if isinstance(data, dict):
for item in data.values():
print_all_leaf_nodes(item)
elif isinstance(data, list) or isinstance(data, tuple):
for item in data:
print_all_leaf_nodes(item)
else:
print data
input:
{'key1': {'key2': 2, 'key3': 1, 'key4' : 1}}
Output:
{'key1': {'key3': 1, 'key4' : 1}}
{'key1': {'key2': 2, 'key4' : 1}}
{'key1': {'key2': 2, 'key3': 1}}
i.e for each iteration, remove a key value pair if its leaf node.
Note: even i am able to get the key path from parent , but not sure how to delete the exact element .
For example if the json is
{ "key1" : { "key2" : { "key3": "value1", "key4" : "value2" }}}
i have the recursive function which returns me a string
key_to_be_removed = "key1.key2.key4"
but i am not sure how to delete key4 using this string.
please help.