Skip to content

Instantly share code, notes, and snippets.

@prabindh
Created May 4, 2019 02:56
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save prabindh/35dfb54249a0b5cfc1550aa8c4bd72f1 to your computer and use it in GitHub Desktop.
Save prabindh/35dfb54249a0b5cfc1550aa8c4bd72f1 to your computer and use it in GitHub Desktop.
Create directory listing tree in python and output in JSON
import os
import json
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
print json.dumps(path_to_dict('.'))
# Output like below
# From https://stackoverflow.com/questions/25226208/represent-directory-tree-as-json
"""
{
"type": "directory",
"name": "hello",
"children": [
{
"type": "directory",
"name": "world",
"children": [
{
"type": "file",
"name": "one.txt"
},
{
"type": "file",
"name": "two.txt"
}
]
},
{
"type": "file",
"name": "README"
}
]
}
"""
@xchellx
Copy link

xchellx commented Jul 14, 2020

#!python3

import os
import json

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

with open('MANIFEST.JSON', 'w', encoding='utf-8') as f:
    json.dump(path_to_dict('.'), f, ensure_ascii=False, indent=4)

So I've modified it to this point. However, my goal is to represent the children as one single object with each child being a key of that single object. However, I don't know an equivalent to the list comprehension here: [path_to_dict(os.path.join(path,x)) for x in os.listdir(path)]

It gives output like this:

{
    ".": {
        "type": "directory",
        "children": [
            {
                "css": {
                    "type": "directory",
                    "children": [
                        {
                            "index.css": {
                                "type": "file"
                            }
                        }
                    ]
                }
            },
            {
                "desktop.ini": {
                    "type": "file"
                }
            },
            {
                "dir2json.py": {
                    "type": "file"
                }
            },

and so on.
However, with this current structure, to access the files in JavaScript, I'd have to do something like filesObj["."]["css"]["children"][0]["index.css"] which is not pretty. That index right there can really mess me up because it would have me to expect to know the name of the file behind an index. filesObj["."]["css"]["children"]["index.css"] would be better in this case but I'm really struggling how to make children a subobject.

EDIT:
I solved it but probably not the correct way. However, the end result was how I wanted it. Apologies if this is incorrect. I just converted the array of dicts into a single dict.

#!python3

import os
import json

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

with open('MANIFEST.JSON', 'w', encoding='utf-8') as f:
    json.dump(path_to_dict('.'), f, ensure_ascii=False, indent=4)

outputs:

{
    ".": {
        "type": "directory",
        "children": {
            "css": {
                "type": "directory",
                "children": {
                    "index.css": {
                        "type": "file"
                    }
                }
            },
            "desktop.ini": {
                "type": "file"
            },
            "dir2json.py": {
                "type": "file"
            },

and so on

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment