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