有什么简单的方法可以生成这样的JSON吗?我发现了os.walk()和os.listdir(),所以我可以递归地降级到目录中并构建一个python对象,但这听起来像是在重新发明轮子,也许有人知道这样的任务的工作代码?
os.walk()
os.listdir()
{ "type": "directory", "name": "hello", "children": [ { "type": "directory", "name": "world", "children": [ { "type": "file", "name": "one.txt" }, { "type": "file", "name": "two.txt" } ] }, { "type": "file", "name": "README" } ] }
我不认为这个任务是一个“轮子”(可以这么说)。但这可以通过您提到的工具轻松实现:
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('.'))