#!/usr/bin/env python3
"""Print out the directory structure as json dict."""

from sys import argv
import json
import os


def path_to_dict(path):
    d = {'name': os.path.basename(path)}
    if os.path.isdir(path):
        d['type'] = "directory"
        d['children'] = [path_to_dict(os.path.join(path,x)) for x in os.listdir\
(path)]
    else:
        d['type'] = "file"
    return d


def validate_path(path):
   return os.path.abspath(path) 


def main():
    try:
        path = validate_path(argv[1])
    except IndexError:
        print('Usage: jsontree <PATH>')
    else:
        print(json.dumps(path_to_dict(path)))


if __name__ == "__main__":
    main()

