Skip to content

Instantly share code, notes, and snippets.

@AntiKnot
Created July 10, 2019 14:24
Show Gist options
  • Select an option

  • Save AntiKnot/41fc9eefe0902229f4c003116a2461ac to your computer and use it in GitHub Desktop.

Select an option

Save AntiKnot/41fc9eefe0902229f4c003116a2461ac to your computer and use it in GitHub Desktop.
convert nested data to flat data
data = [
{
'id': '1',
'parent': '',
'children': [
{
'id': '2',
'parent': '1',
'children': [
{
'id': '8',
'parent': '2',
'children': [
{
'id': '9',
'parent': '8'
}
]
}
]
},
{
'id': '3',
'parent': '1'
}
]
},
{
'id': '4',
'parent': '',
'children': [
{
'id': '5',
'parent': '4'
},
{
'id': '6',
'parent': '4'
},
{
'id': '7',
'parent': '4'
}
]
}
]
def nested2flat(nested: list) -> list:
res = []
for child in nested:
children = child.pop('children', [])
res.append(child)
res.extend(nested2flat(children))
return res
if __name__ == '__main__':
print(nested2flat(data))
"""
result = [
{'id': '1', 'parent': ''},
{'id': '2', 'parent': '1'},
{'id': '8', 'parent': '2'},
{'id': '9', 'parent': '8'},
{'id': '3', 'parent': '1'},
{'id': '4', 'parent': ''},
{'id': '5', 'parent': '4'},
{'id': '6', 'parent': '4'},
{'id': '7', 'parent': '4'}
]
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment