Python folder structure with children to JSON
<p>I have a script that turns any given folder structure into a JSON, JSTree compatible structure.   However child folders are all grouped under one level of child.  So folders within folders are marked as just one level under the root.  How could I maintain the root-child-child relationship within JSON?  </p>

<pre><code>import os, sys, json

def all_dirs_with_subdirs(path, subdirs):

    try:
        path = os.path.abspath(path)

        result = []
        for root, dirs, files in os.walk(path):
            exclude = "Archive", "Test"
            dirs[:] = [d for d in dirs if d not in exclude]
            if all(subdir in dirs for subdir in subdirs):
                    result.append(root)
        return result

    except WindowsError:
        pass
def get_directory_listing(path):
    try:
        output = {}
        output["text"] = path.decode('latin1')
        output["type"] = "directory"
        output["children"] = all_dirs_with_subdirs("G:\TEST", ('Maps', 'Temp'))
        return output

    except WindowsError:
        pass
with open(r'G:\JSONData.json', 'w+') as f:
    listing = get_directory_listing("G:\TEST")
    json.dump(listing, f)
</code></pre>

<p>You have only a one level hierarchy because in <code>all_dirs_with_dubdirs</code> you walk through the directory tree and append every valid directory to a flat list <code>result</code> which you then store in the only <code>"children"</code> key.</p>

<p>What you want to do is to create a structure like</p>

<pre><code>{
  'text': 'root_dir',
  'type': 'directory',
  'children': [
     {
       'text': 'subdir1 name',
       'type': 'directory',
       'children': [
         {
           'text': 'subsubdir1.1 name',
           'type': 'directory',
           'children': [
             ...
           ]
         },
         ...
       ]
     },
     {
       'text': 'subdir2 name',
       'type': 'directory',
       'children': [
         ...
       ]
     },
  ]
}
</code></pre>

<p>You could do this quite elegantly with recursion</p>

<pre><code>def is_valid_dir(path, subdirs):
    return all(os.path.isdir(path) for subdir in subdirs)


def all_dirs_with_subdirs(path, subdirs):
    children = []

    for name in os.listdir(path):
        subpath = os.path.join(path, name)
        if name not in ("Archive", "Test") and os.path.isdir(subpath) and is_valid_dir(subpath, subdirs):
            children.append({
                'text': name,
                'type': 'directory',
                'children': all_dirs_with_subdirs(subpath, subdirs)
            })

    return children
</code></pre>

python json jstree