【问题标题】:Convert file paths into JSON structure using bash / jq使用 bash / jq 将文件路径转换为 ​​JSON 结构
【发布时间】:2020-01-13 04:59:00
【问题描述】:

我们可以使用 jq for 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 bash jq directory-structure pathname


【解决方案1】:

以下假设:

  • 输入是“/”式文件路径名的有效 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"
    ]
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    • 2018-08-20
    • 2021-12-05
    相关资源
    最近更新 更多