[英]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:以下假设:
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"
]
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.