将目录树表示为JSON

And*_*eev 17 python tree json python-2.7 data-structures

有没有简单的方法来生成这样的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"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

Ema*_*ini 31

我不认为这个任务是"轮子"(可以这么说).但是你可以通过你提到的工具轻松实现这一点:

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('.'))
Run Code Online (Sandbox Code Playgroud)

  • 这是递归的。 (4认同)

小智 13

在Linux上,tree可以使用命令行工具,但默认情况下不会安装它.输出几乎与OP所需的输出相同,使用-JJSON输出的标志(例如,可以将其流式传输到文件):

tree -J folder
Run Code Online (Sandbox Code Playgroud)

在OSX上,可以通过Homebrew安装此工具.

  • 我在 [手册页](https://linux.die.net/man/1/tree) 上没有看到 `-J` 标志。是否有特定版本的 `tree` 具有 json 输出? (2认同)