Created
May 4, 2019 02:56
-
-
Save prabindh/35dfb54249a0b5cfc1550aa8c4bd72f1 to your computer and use it in GitHub Desktop.
Create directory listing tree in python and output in JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | |
} | |
] | |
} | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
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.
outputs:
and so on