Script to Generate Directory Structure in JSON

This script recursively generates the directory structure of the current directory and outputs it in JSON format. It uses the os module to navigate directories.
mail@pastecode.io avatar
unknown
python
17 days ago
590 B
1
Indexable
Never
import os
import json

def get_structure(path):
    structure = {}
    for item in os.listdir(path):
        item_path = os.path.join(path, item)
        if os.path.isdir(item_path):
            structure[item] = get_structure(item_path)
        else:
            structure[item] = None
    return structure

# Get the current directory
current_dir = os.path.dirname(os.path.abspath(__file__))

# Get the structure
project_structure = {os.path.basename(current_dir): get_structure(current_dir)}

# Convert to JSON and print
print(json.dumps(project_structure, indent=2))
Leave a Comment