A question on the StackOverflow:
Put the following format:
[{"id": 1, "title": "Node1", "parent": "NULL"},{"id": 2, "title": "Node2", "Parent": 1},{"id": 3, "title": "Node3", "Parent": 1},{"id": 4, "title": "Node4", "Parent": 2},{"id": 5, "title": "Node5", "Parent": 2}]
Change to:
[{ ' id ':1, ' Title ': ' Node1 ', ' Childs ':[ { ' id ':2, ' title ': ' Node2 ' ' Childs ':[ { ' id ':4, ' title ': ' Node4 ', ' Childs ':  []  &NBsp; }, { ' id ':5, ' title ': ' Node5 ', ' Childs ': [] } ] }, { ' id ':3, ' title ': ' Node3 ' &NBsp; ' Childs ':[] } ] }]
Related code: (mainly using the variability of Python objects, such as dict,list are variable.) so that the depth of the data can be simplified)
result, t = [], {}for i in K: # K for the above data, K recommended to sort by parent i[' childs ' = [] if i[' parent '] = = ' null ': Del i[' parent '] result.append (i) t[1] = Result[0] else:t[i[' parent ']][' Childs '].append (i) t[i [' ID ']] = t[i[' parent ']][' Childs '][-1] del t[i[' parent ']][' Childs '][-1][' parent ']print result
Results:
z:\download>k.py[{' Childs ': [{' Childs ': [{' Childs ': [], ' ID ': 4, ' title ': ' Node4 '}, {' Childs ': [], ' ID ': 5, ' title ': ' N ' Ode5 '}], ' ID ': 2, ' title ': ' Node2 '}, {' Childs ': [], ' ID ': 3, ' title ': ' Node3 '}], ' ID ': 1, ' title ': ' Node1 '}]
Python inline list formatting