Конвертировать пути к файлам в структуру JSON, используя bash / jq - PullRequest
0 голосов
/ 13 января 2020

Можем ли мы преобразовать приведенный ниже пример, используя jq для bash (https://stedolan.github.io/jq/)?

Требуется преобразовать пути к файлам в json, как указано ниже пример

const data = [
    "/parent/child1/grandchild1"
    "/parent/child1/grandchild2"
    "/parent/child2/grandchild1"
];

const output = {};
let current;

for (const path of data) {
    current = output;

    for (const segment of path.split('/')) {
        if (segment !== '') {
            if (!(segment in current)) {
                current[segment] = {};
            }

            current = current[segment];
        }
    }
}

console.log(output);

1 Ответ

0 голосов
/ 13 января 2020

Предполагается следующее:

  • входные данные являются допустимыми JSON массивом имен файлов в стиле "/";
  • все пути являются абсолютными (т. Е. Начинаются с "/").
reduce .[] as $entry ({};
  ($entry | split("/") ) as $names
   | $names[1:-1] as $p
   | setpath($p; getpath($p) + [$names[-1]]) )

Пример

Вход

[
    "/parent/child1/grandchild1",
    "/parent/child1/grandchild2",
    "/parent/child2/grandchild3",
    "/parent/child2/grandchild4",
    "/parent2/child2/grandchild5"
]

Выход

{
  "parent": {
    "child1": [
      "grandchild1",
      "grandchild2"
    ],
    "child2": [
      "grandchild3",
      "grandchild4"
    ]
  },
  "parent2": {
    "child2": [
      "grandchild5"
    ]
  }
}
...