简体   繁体   English

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

[英]Convert file paths into JSON structure using bash / jq

Can we convert the below example using jq for bash ( https://stedolan.github.io/jq/ )?我们可以使用 jq for bash ( https://stedolan.github.io/jq/ ) 转换以下示例吗?

The requirement is to convert the file paths into json as given in the below example要求是将文件路径转换为 ​​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);

The following assumes:以下假设:

  • the input is a valid JSON array of "/"-style pathnames of files;输入是一个有效的“/”样式文件路径名的 JSON 数组;
  • pathnames are all absolute (ie, begin with "/").路径名都是绝对的(即以“/”开头)。
reduce .[] as $entry ({};
  ($entry | split("/") ) as $names
   | $names[1:-1] as $p
   | setpath($p; getpath($p) + [$names[-1]]) )

Example例子

Input输入

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

Output输出

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM