Search code examples
pythonjsondirectorystructure

Render JSON to directory structure in Python


I would like to store a JSON structure which holds projects and files I am currently working on. File structure looks like this:

|-project1
|--sequence1
|----file1.ext
|----file2.ext
|-project2
|--sequence1
|----file1.ext
|----file2.ext
|-project3
|--sequence3
|----file1.ext
|----file2.ext

JSON version would look like this:

data = [
  {
    type: "folder",
    name: "project1",
    path: "/project1",
    children: [
      {
        type: "folder",
        name: "sequence1",
        path: "/project1/sequence1",
        children: [
          {
            type: "file",
            name: "file1.ext",
            path: "/project1/sequence1/file1.ext"
          } , {
            type: "file",
            name: "file2.ext",
            path: "/project1/sequence1/file2.ext"

            ...etc
          }
        ]
      }
    ]
  }
]

Is it possible to render this structure to actual directories and files using Python? (it can be empty files). On the other hand, I would like to build a function traversing existing directories, returning similar JSON code.


Solution

  • This should be easy enough to create the dictionary using a recursive function and some of the goodies in the os module...:

    import os
    
    def dir_to_list(dirname, path=os.path.pathsep):
        data = []
        for name in os.listdir(dirname):
            dct = {}
            dct['name'] = name
            dct['path'] = path + name
    
            full_path = os.path.join(dirname, name)
            if os.path.isfile(full_path):
                dct['type'] = 'file'
            elif os.path.isdir(full_path):
                dct['type'] = 'folder'
                dct['children'] = dir_to_list(full_path, path=path + name + os.path.pathsep)
            data.append(dct)
        return data
    

    untested

    Then you can just json.dump it to a file or json.dumps it to a string. . .