将目录树表示为 JSON [英] Represent directory tree as JSON
本文介绍了将目录树表示为 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么简单的方法可以生成这样的 JSON?我找到了 os.walk()
和 os.listdir()
,所以我可以递归下降到目录中并构建一个 python 对象,好吧,但这听起来像是重新发明了一个轮子,也许有人知道此类任务的工作代码?
Is there any easy way to generate such a JSON? I found os.walk()
and os.listdir()
, so I may do recursive descending into directories and build a python object, well, but it sounds like reinventing a wheel, maybe someone knows working code for such a task?
{
"type": "directory",
"name": "hello",
"children": [
{
"type": "directory",
"name": "world",
"children": [
{
"type": "file",
"name": "one.txt"
},
{
"type": "file",
"name": "two.txt"
}
]
},
{
"type": "file",
"name": "README"
}
]
}
推荐答案
我不认为这个任务是一个轮子"(可以这么说).但是,您可以通过您提到的工具轻松实现这一目标:
I don't think that this task is a "wheel" (so to speak). But it is something which you can easily achieve by means of the tools you mentioned:
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('.'))
这篇关于将目录树表示为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文