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 can get the immediate children of the CWD with:</p>

<pre><code>next(os.walk('.'))[1]
</code></pre>

<p>With that expression you could write a recursive traversal function like this:</p>

<pre><code>def dir_to_json(dir):
    subdirs = next(os.walk('dir'))[1]
    if not subdirs:
        return # Something in your base case, how are you representing this?
    return combine_as_json(dir_to_json(os.path.join(dir, d)) for d in subdirs)
</code></pre>

<p>Then you need to make a <code>combine_as_json()</code> function that aggregates the subdir results in your chosen encoding/representation.</p>

python json jstree