使用 bash / jq 将文件路径转换为 ​​JSON 结构

Convert file paths into JSON structure using bash / jq

我们可以使用 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);

以下假设:

  • 输入是有效的 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"
    ]
  }
}