Dennis Dmitriev | de847d9 | 2017-06-26 18:58:05 +0300 | [diff] [blame^] | 1 | |
| 2 | def get_nested_key(data, path=None): |
| 3 | if type(path) is not list: |
| 4 | raise("Use 'list' object with key names for 'path'") |
| 5 | for key in path: |
| 6 | value = data.get(key, None) |
| 7 | if value: |
| 8 | data = value |
| 9 | else: |
| 10 | return None |
| 11 | return data |
| 12 | |
| 13 | |
| 14 | def remove_nested_key(data, path=None): |
| 15 | if type(path) is not list: |
| 16 | raise("Use 'list' object with key names for 'path'") |
| 17 | |
| 18 | # Remove the value from the specified key |
| 19 | val = get_nested_key(data, path[:-1]) |
| 20 | val[path[-1]] = None |
| 21 | |
| 22 | # Clear parent keys if empty |
| 23 | while path: |
| 24 | val = get_nested_key(data, path) |
| 25 | if val: |
| 26 | # Non-empty value, nothing to do |
| 27 | return |
| 28 | else: |
| 29 | get_nested_key(data, path[:-1]).pop(path[-1]) |
| 30 | path = path[:-1] |
| 31 | |
| 32 | |