Below is my data.
input = {'key1': {'key1.1': 'value1.1',
'key1.2': 'value1.2',
'key1.3': {'key1.3.1': 'value1.3.1', 'key1.3.2': [{'key1.3.2.1': 'value1.3.2.1'},
{'key1.3.2.2': 'value1.3.2.2'}
]
}
},
'key2': 'value2'}
I want to recursively convert inner inner key/values into a list of sub dictionaries with Name and Value as their keys. Below is my desired output.
output = {"key1": [{"NAME": "key1.1", "VALUE": "value1.1"},
{"NAME": "key1.2", "VALUE": "value1.2"},
{"NAME": "key1.3", "VALUE": [{"NAME": "key1.3.1", "VALUE": "value1.3.1"},
{"NAME": "key1.3.2", "VALUE": [{"NAME": "key1.3.2.1", "VALUE": "value1.3.2.1"},
{"NAME": "key1.3.2.2", "VALUE": "value1.3.2.2"}]
}]
}],
"key2": "value2"}
Below is what is tried but it is not working correctly for list of dictionaries (ex: "key1.3.2.1": "value1.3.2.1"). Is there a way to achieve this output?
def my_func(d):
new_dict = {}
for k, v in d.items():
a = []
if isinstance(v, dict):
for key, value in my_func(v).items():
x = {}
y = {}
x['NAME'] = key
y['VALUE'] = value
z = {**x, **y}
a.append(z)
elif isinstance(v, list):
a = [my_func(item) if isinstance(item, dict) else item for item in v]
else:
a = v
new_dict[k] = a
return new_dict
output = json.dumps(my_func(input), indent=2)
print(output)
inputas variable name, you're shadowing built-in function.