Skip to content

Instantly share code, notes, and snippets.

@luizhenriquefbb
Last active March 16, 2020 18:40
Show Gist options
  • Save luizhenriquefbb/e2eb8ba920b49ae72420de97549341e0 to your computer and use it in GitHub Desktop.
Save luizhenriquefbb/e2eb8ba920b49ae72420de97549341e0 to your computer and use it in GitHub Desktop.
[python] show a folder content in a JSON format

Linux / Mac Folder to JSON

Prints a folder in a JSON format

python main.py <path> > <output_file.json>
#!/usr/bin/env python
import os
import errno
names_to_ignore = [
".DS_Store"
]
def file_to_json(path):
hierarchy = {
'type': 'folder',
'name': os.path.basename(path),
# 'path': path,
}
try:
hierarchy['children'] = []
for contents in os.listdir(path):
children_path = os.path.join(path, contents)
children_name = os.path.basename(children_path)
if children_name in names_to_ignore:
continue
hierarchy['children'].append(file_to_json(children_path))
except OSError as e:
if e.errno != errno.ENOTDIR:
raise
hierarchy['type'] = 'file'
return hierarchy
if __name__ == '__main__':
import json
import sys
try:
directory = sys.argv[1]
except IndexError:
directory = "."
print(json.dumps(file_to_json(directory), indent=2, sort_keys=True))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment