Создание JSON дерева каталогов с использованием JQ - PullRequest
0 голосов
/ 26 сентября 2018

Я пытаюсь построить JSON из дерева каталогов, используя jq .Я на полпути, но дерево каталогов плоское, и мне нужно поместить каждый каталог в его родительский children массив.

Код, который у меня пока есть, dirtree.jq:

[
    split("\n\n") as $list

    | $list
    | .[0]
    | split("\n")
    | .  + [  .[0] | split("\\") | .[0:-1] | join("\\")  ] # add root folder
    | sort
    | . as $folders

    | $list
    | .[1]
    | split("\n") as $files

    | $folders [] as $parent


    | {
        path: $parent,
        children: (
            $files
            | map({
                path: select(
                    . | (split("\\") | .[0:-1] | join("\\")) as $fileParent # get parent path
                      | $fileParent == $parent
                )
            })
        )
    }



] as $flatTree
| $flatTree

Файл input представляет собой raw простой текстовый файл в листинге формата:

  • first all каталоги данной папки

  • , затем пустая строка

  • , затем список всех files :


C:\Program Files\7-Zip
C:\Program Files\ASUS
C:\Program Files\Common Files
C:\Program Files\Intel
C:\Program Files\Internet Explorer
C:\Program Files\Mozilla Firefox
C:\Program Files\MSBuild
C:\Program Files\NVIDIA Corporation
C:\Program Files\Realtek
.
.
.
C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.0.0.1\en-US
C:\Program Files\WindowsPowerShell\Modules\PSReadline\1.2
C:\Program Files\WindowsPowerShell\Modules\PSReadline\1.2\en
                <-- NOTE THIS EMPTY LINE (\n\n) that separates folders from files
C:\Program Files\desktop.ini
C:\Program Files\7-Zip\7-zip.chm
C:\Program Files\7-Zip\7-zip.dll
C:\Program Files\7-Zip\7-zip32.dll
C:\Program Files\7-Zip\7z.dll
C:\Program Files\7-Zip\7z.exe
C:\Program Files\7-Zip\7z.sfx
C:\Program Files\7-Zip\7zCon.sfx
C:\Program Files\7-Zip\7zFM.exe
C:\Program Files\7-Zip\7zG.exe
C:\Program Files\7-Zip\descript.ion
.
.
.
C:\Program Files\WindowsPowerShell\Modules\PSReadline\1.2\Microsoft.PowerShell.PSReadline.dll
C:\Program Files\WindowsPowerShell\Modules\PSReadline\1.2\PSReadline.psd1
C:\Program Files\WindowsPowerShell\Modules\PSReadline\1.2\PSReadline.psm1
C:\Program Files\WindowsPowerShell\Modules\PSReadline\1.2\en\Microsoft.PowerShell.PSReadline.Resources.dll

Полученный json имеет все файлы, добавленные к их родителям, но теперь мне нужно переместить каждую папку в parent children массив :


enter image description here

Командная строка:

jq -R --slurp -s -f dirtree.jq input.txt > dirtree.json

1 Ответ

0 голосов
/ 27 сентября 2018

Следующее, вероятно, не совсем то, что вам нужно, но должно помочь вам в этом:

def parsePathname: split("\\") | {path: .[0:length-1], file: .[-1]};

# skip over lines that only specify directories
def pathnames:
  foreach inputs as $x (null;
    if . == null
    then if ($x|length) == 0 then 0 else . end
    else .+1
    end;
    select(. and . > 0)|$x)
    | parsePathname ;

reduce pathnames as $pn ({};
  getpath($pn.path + ["children"]) as $children
  | setpath($pn.path + ["children"]; $children + [$pn.file]) )

Вывод

Когда ваш список обрезан из ориентировочных строк, выполните следующую команду:

jq -R -n -f dirtree.jq dirtree.txt

производит:

{
  "C:": {
    "Program Files": {
      "children": [
        "desktop.ini"
      ],
      "7-Zip": {
        "children": [
          "7-zip.chm",
          "7-zip.dll",
          "7-zip32.dll",
          "7z.dll",
          "7z.exe",
          "7z.sfx",
          "7zCon.sfx",
          "7zFM.exe",
          "7zG.exe",
          "descript.ion"
        ]
      },
      "WindowsPowerShell": {
        "Modules": {
          "PSReadline": {
            "1.2": {
              "children": [
                "Microsoft.PowerShell.PSReadline.dll",
                "PSReadline.psd1",
                "PSReadline.psm1"
              ],
              "en": {
                "children": [
                  "Microsoft.PowerShell.PSReadline.Resources.dll"
                ]
              }
            }
          }
        }
      }
    }
  }
}
...