无限递归目录生成 json格式数据, jstree数据源

时间:2022-07-24 11:41:07
无限递归目录生成 json格式数据, jstree数据源 在前面的博文中有了用 java写的无限递归目录生成 json格式数据,由于我 apache+mod_pathon要用 python写,所以又重新写了一个,放上来供参考。  输入:  path="E/test" 这是要遍历的目录。 输出:输出结果保存在文件“ E:/root.json”
import os
import glob

def fun(path,parent):
global Id
global jsonstr
global count

for i,fn in enumerate(glob.glob(path + os.sep + '*' )):

if os.path.isdir(fn):
jsonstr+='''{"attributes":{"id":"'''+ str(Id)+'''"},"parent":"'''+str(parent)+'''","state":{"opened":false},"text":"'''+os.path.basename(fn)+'''","children":['''
parent=Id
Id+=1
for j,li in enumerate(glob.glob(fn + os.sep + '*' )):

if os.path.isdir(li):
jsonstr+='''{"attributes":{"id":"'''+ str(Id)+'''"},"parent":"'''+str(parent)+'''","state":{"opened":false},"text":"'''+os.path.basename(li)+'''","children":['''
parent=Id
Id+=1
fun(li,parent)
jsonstr+="]}"
if j<len(glob.glob(fn + os.sep + '*' ))-1:
jsonstr+=","

else:
jsonstr+='''{"attributes":{"id":"'''+ str(Id)+'''"},"parent":"'''+str(parent)+'''","state":{"opened":false},"text":"'''+os.path.basename(li)+'''","type":"leaf"}'''
Id+=1
if j<len(glob.glob(fn + os.sep + '*' ))-1:
jsonstr+=","
jsonstr+="]}"
if i<len(glob.glob(path + os.sep + '*' ))-1:
jsonstr+=","

else:

jsonstr+='''{"attributes":{"id":"'''+ str(Id)+'''"},"parent":"'''+str(parent)+'''","state":{"opened":false},"text":"'''+os.path.basename(fn)+'''","type":"leaf"}'''
Id+=1
if i<len(glob.glob(path + os.sep + '*' ))-1:
jsonstr+=","
return jsonstr

path="E:/java"
parent=0
Id=0
jsonstr="["
jsonstr=fun(path,0)
jsonstr+="]"
file_object = open('E:/root.json', 'w')
file_object.write(jsonstr)
file_object.close()