将目录树表示为JSON

编程入门 行业动态 更新时间:2024-10-11 15:20:45
本文介绍了将目录树表示为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:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651219.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:目录   JSON

发布评论

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

>www.elefans.com

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