Infinity8 Infinity8 - 8 months ago 40
JSON Question

Python export list of folders & full path as JSON for JSTree

I am trying to create a JSON file for jstree. But I'm having trouble getting this code to output the full path of the folders and only show folders. I am new to Python and would appreciate any insight!

The goal is to have users select a folder and bring back the full path of that folder in JSTree. (Not in this code).

import os
import json

def path_to_dict(path):
d = {'text': os.path.basename(path)}
if os.path.isdir(path):
d['type'] = "directory"
for root, directories, filenames in os.walk('U:\PROJECTS\MXD_to_PDF'):
for directory in directories:
d['path']= os.path.join(root, directory)
d['children'] = [path_to_dict(os.path.join(path,x)) for x in os.listdir\

d['type'] = "file"
#del d["type"]

return d

print json.dumps(path_to_dict('U:\PROJECTS\MXD_to_PDF\TEST'))

with open('U:\PROJECTS\MXD_to_PDF\TEST\JSONData.json', 'w') as f:
json.dump(path_to_dict('U:\PROJECTS\MXD_to_PDF\TEST'), f)


"text": "TEST"
, "type": "directory"
, "children": [{
"text": "JSONData.json"
, "type": "file"
}, {
"text": "Maps"
, "type": "directory"
, "children": [{
"text": "MAY24MODIFIED.mxd"
, "type": "file"
}, {
"text": "MAY24MODIFIED 2016-05-24 16.16.16.pdf"
, "type": "file"
}, {
"text": "testst"
, "type": "directory"
, "children": []
, "path": "U:\\PROJECTS\\MXD_to_PDF\\TEST2\\Maps\\exported"
, "path": "U:\\PROJECTS\\MXD_to_PDF\\TEST2\\Maps\\exported"
, "path": "U:\\PROJECTS\\MXD_to_PDF\\TEST2\\Maps\\exported"



For me the following solution works: (you wanted only directories)

def get_list_of_dirs(path):
    output_dictonary = {}
    list_of_dirs = [os.path.join(path, item) for item in os.listdir(path) if os.path.isdir(os.path.join(path, item))]
    output_dictonary["text"] = path
    output_dictonary["type"] = "directory"

    output_dictonary["children"] = []

    for dir in list_of_dirs:
    return output_dictonary


(You can insert the import, your path, and saving to file as you wish)