我如何用jq解析这个json结构?它应该递归地遍历叶子(项目和组)。
我的用例是:用CLI在VCS中创建项目和组。组可以有多个项目,组可以为空,项目必须有预先创建的父组
类似的类比是:
- group = folder
- project = file
- path =
/root-groups/nested-groups-level-1/nested-groups-level-2/nested-groups-level-N
格式的绝对路径
{
"structure":[
{
"name":"rootgroup1",
"type":"group",
"nested":[
{
"name":"nestedproject1",
"type":"project"
},
{
"name":"nestedgroup1",
"type":"group",
"nested":[
{
"name":"nestednestedproject2",
"type":"project"
}
]
}
]
},
{
"name":"rootproject1",
"type":"project"
},
{
"name":"rootgroup2",
"type":"group",
"nested": []
}
]
}
预期输出:
"rootgroup1","group",""
"nestedproject1","project","rootgroup1"
"nestedgroup1","group","rootgroup1"
"nestednestedproject2","group","rootgroup1/nestedgroup1"
"rootproject1","project",""
"rootgroup2","group",""
试题:
jq -r '.structure[] | .. | "(.name?) (.type?)"'
仍然不确定,如何创建父路径
根据我的理解,下面实现了解决问题的方法:
# $prefix is an array interpreted as the prefix
def details($prefix):
def out:
select(has("name") and has("type")) | [.name, .type, "/" + ($prefix|join("/"))];
out,
if (.nested | (. and length>0))
then .name as $n | .nested[] | details($prefix + [$n])
else empty
end;
.structure[]
| details([])
| @csv
给定示例输入,输出将是:
"rootgroup1","group","/"
"nestedproject1","project","/rootgroup1"
"nestedgroup1","group","/rootgroup1"
"nestednestedproject2","project","/rootgroup1/nestedgroup1"
"rootproject1","project","/"
"rootgroup2","group","/"
这与示例输出在某些方面有所不同,但希望您可以从这里了解它。