将目录树表示为 JSON

编程入门 行业动态 更新时间:2024-10-11 17:29:24
本文介绍了将目录树表示为 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

本文发布于:2023-11-30 19:25:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651218.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:目录   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!