python生成前端目录树zTree插件需要的数据格式
一、首先准备数据
ll= ['/app/',
'/nficd/test_app/htmlname.py',
'/nficd/test_app/migrations/',
'/nficd/test_app/migrations/models.py',
'/nficd/test_app/migrations/sec_audit.log',
'/nficd/test_app/templates/',
'/nficd/test_app/templates/test_app/',
'/nficd/test_app/templates/test_app/set.html',
'/nficd/test_app/tests.py',
'/nficd/test_app/urls.py',
'/nficd/test_app/log.py',]
二、处理数据格式
1、按行处理数据,并将结果返回
代码:
if __name__ == '__main__':
for l in ll:
tree = test_1(l)
current = test_3(tree, current)
print(current)
返回值tree数据(随机一条):
[{'text': 'nficd', 'children': [{'text': 'test_app', 'children': [{'text': 'htmlname.py'}]}]}]
函数test_1():
def test_1(l):
isDir = False
if l[-1] == '/':
l_list = l[1:-1].split('/')
isDir = True
else:
l_list = l[1:].split('/')
return test_2([], l_list, isDir)
函数test_2():
def test_2(list, l_list, isDir):
if not isDir and len(l_list) == 1:
list.append({"text": l_list[0]})
l_list.remove(l_list[0])
return list
for ls in l_list:
x1 = []
list.append({"text": ls, "children": x1})
l_list.remove(ls)
test_2(x1, l_list, isDir)
return list
2、将1中的每行结果处理,写入到list数组中
上面提到的代码:current = test_3(tree, current)
函数test_3():
def test_3(tree, current):
if len(tree) > 0 and len(current) == 0:
current.append(tree[0])
else:
text = tree[0]['text']
key_exist = [i['text'] for i in current]
if text not in key_exist:
current.append(tree[0])
else:
index = key_exist.index(text)
test_3(tree[0]["children"], current[index]["children"])
return current
上面结尾:print(current)
格式化输出结果:
[{
'text': 'app',
'children': []
}, {
'text': 'nficd',
'children': [{
'text': 'test_app',
'children': [{
'text': 'htmlname.py'
}, {
'text': 'migrations',
'children': [{
'text': 'models.py'
}, {
'text': 'sec_audit.log'
}]
}, {
'text': 'templates',
'children': [{
'text': 'test_app',
'children': [{
'text': 'set.html'
}]
}]
}, {
'text': 'tests.py'
}, {
'text': 'urls.py'
}, {
'text': 'log.py'
}]
}]
}]
这里进行了格式化,代码里面并没有实现
代码不够美观,也肯定有更好的方法,主要是自己写的,记录一下,如果有更好的,请告诉我,学习学习