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

来源:互联网 发布:js slibings 编辑:程序博客网 时间:2024/05/19 17:52
无限递归目录生成 json格式数据, jstree数据源
在前面的博文中有了用 java写的无限递归目录生成 json格式数据,由于我 apache+mod_pathon要用 python写,所以又重新写了一个,放上来供参考。 
输入:  path="E/test" 这是要遍历的目录。
输出:输出结果保存在文件“ E:/root.json”
import osimport globdef 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 jsonstrpath="E:/java"parent=0Id=0jsonstr="["         jsonstr=fun(path,0)jsonstr+="]"file_object = open('E:/root.json', 'w')file_object.write(jsonstr)file_object.close()


0 0