本文介绍了将目录树表示为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
发布评论