Solution for this problem
import json
inp = {}
cout = {}
def flatrn_dict(inp, name, pk_name):
cop_in = inp.copy()
pkn, pkv = identify_id(cop_in)
for k, v in cop_in.items():
if type(v) == dict:
if pkv is not None:
v.update({pkn: pkv})
flatrn_dict(v, k, name)
inp.pop(k)
elif type(v) == list:
for vx in v:
if pkn is not None:
pkn = "{0}_id".format(pk_name)
vx.update({pkn: pkv})
flatrn_dict(vx, k, name)
arr = cout.get(name)
if arr is None:
cout.update({name: v})
else:
arr.extend(v)
cout.update({name: arr})
inp.pop(k)
def identify_id(ele):
for k,v in ele.items():
if 'id' in k.lower():
return k, v
return None, None
if __name__ == "__main__":
with open("test1.json", "r") as f:
inp = json.load(f)
flatrn_dict(inp, "prop", "")
with open("test_out.json", "w") as fw:
fw.write(json.dumps(cout))
solved How to handle nested list inside nested dict in Python? [closed]