Mateusz Wójt
Mateusz Wójt

Reputation: 139

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.

Upvotes: 4

Views: 4284

Answers (2)

mgilson
mgilson

Reputation: 310049

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. . .

Upvotes: 3

tmdag
tmdag

Reputation: 529

If you happen to use Unix based system, you could use "tree" command

$ tree -Jd . > folderTemplate.json

or from Python:

import subprocess
data = subprocess.run(["tree", "-Jd", "/path/to/dir"], stdout=subprocess.PIPE)
print(data.stdout)

Then it would be simple to convert it back to directory structure with Python. Maybe this might be helpful: https://github.com/tmdag/makedirtree

Upvotes: 0

Related Questions