代码之家  ›  专栏  ›  技术社区  ›  Andrey Moiseev Ashraf Ali

将目录树表示为JSON

  •  32
  • Andrey Moiseev Ashraf Ali  · 技术社区  · 12 年前

    有什么简单的方法可以生成这样的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 回复  |  直到 12 年前
        1
  •  48
  •   Emanuele Paolini    11 年前

    我不认为这项任务是一个“轮子”(可以这么说)。但这是您可以通过您提到的工具轻松实现的:

    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('.'))
    
        2
  •  24
  •   Jonathan H    8 年前

    在Linux上,命令行工具 tree 可以使用,尽管它是 默认安装。使用标志,输出几乎与OP所需的输出相同 -J 对于JSON输出(例如,可以将其流式传输到文件):

    tree -J folder
    

    在OSX上,可以通过 Homebrew .

        3
  •  1
  •   lost    6 年前

    我只是不得不这样做(好吧,差不多),所以点击这个页面,但 above 不会递归到子目录中。

    所以这个版本只处理目录,不处理文件,但是你可以添加这些。

    首先生成嵌套的python dict:

    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 单元