将目录树表示为JSON

33 投票
3 回答
32511 浏览
提问于 2025-04-18 16:43

有没有简单的方法来生成这样的JSON文件?我发现了os.walk()os.listdir()这两个函数,可以用它们递归地进入文件夹,构建一个Python对象。不过,这听起来像是在重复造轮子,可能有人知道已经可以用的代码来完成这个任务?

{
  "type": "directory",
  "name": "hello",
  "children": [
    {
      "type": "directory",
      "name": "world",
      "children": [
        {
          "type": "file",
          "name": "one.txt"
        },
        {
          "type": "file",
          "name": "two.txt"
        }
      ]
    },
    {
      "type": "file",
      "name": "README"
    }
  ]
}

3 个回答

2

我刚刚需要做这个(差不多吧),所以找到了这个页面,但上面的内容并没有递归到子目录里。

所以这个版本只处理目录,不处理文件,不过你可以自己加上文件的处理。

首先生成一个嵌套的 Python 字典:

def fs_tree(root):
    results = {}
    for (dirpath, dirnames, filenames) in os.walk(root):
        parts = dirpath.split(os.sep)
        curr = results
        for p in parts:
            curr = curr.setdefault(p, {})
    return results

其次,使用 json 模块把它转换成 JSON 格式。

27

在Linux系统中,可以使用命令行工具 tree,不过这个工具默认是没有安装的。它的输出格式几乎和提问者需要的一样,只需要加上 -J 这个选项,就可以得到JSON格式的输出(然后可以把这个输出保存到文件中,比如说):

tree -J folder

在OSX系统上,可以通过 Homebrew 来安装这个工具。

51

我觉得这个任务并不是“重复造轮子”。不过,你可以很轻松地用你提到的工具来完成这个任务:

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('.'))

撰写回答