树状结构扁平化处理
作者:互联网
有这样一个树状结构:
data = [ { "id":1, "name":"吃喝", "parentId":0, "children":[ { "id":2, "name":"烧烤", "parentId":"1", "children":[] }, { "id":5, "name":"奶茶", "parentId":"1", "children":[] } ] }, { "id":3, "name":"玩乐", "parentId":0, "children":[ { "id":4, "name":"ktv", "parentId":"3", "children":[] }, { "id":6, "name":"棋牌室", "parentId":"3", "children":[] } ] } ]
现在要将其扁平化处理,存进自关联表里,可以编写函数:
def func(source, result, parent_id): """树状结构扁平化处理""" if source: for item in source: _dict = deepcopy(item) _dict.pop("children") result.append(_dict) tree_zip(item.get("children"), result, item.get("id")) return result
调用方式:
func(data, [], 0)
结果:
data = [
{'id': 1, 'name': '吃喝', 'parentId': 0},
{'id': 2, 'name': '烧烤', 'parentId': '1'}, {'id': 5, 'name': '奶茶', 'parentId': '1'},
{'id': 3, 'name': '玩乐', 'parentId': 0}, {'id': 4, 'name': 'ktv', 'parentId': '3'},
{'id': 6, 'name': '棋牌室', 'parentId': '3'}
]
标签:扁平化,树状,处理,children,item,result,parentId,id,name 来源: https://www.cnblogs.com/liudaya/p/16524692.html