我有一个包含组和子组的JSON对象数组,如下所示:
[
{
"Group name": "Elevation",
"Subgroup": "Contours",
"name": "Contours - Labels"
},
{
"Group name": "Elevation",
"Subgroup": "Contours",
"name": "Contours"
},
{
"Group name": "Elevation",
"Subgroup": "Cuttings",
"name": "Cuttings"
},
{
"Group name": "Framework",
"Subgroup": "Reserves",
"name": "Reserves"
},
{
"Group name": "Framework",
"Subgroup": "Indigenous Reserves",
"name": "Reserves"
},
{
"Group name": "Framework",
"Subgroup": "Land Borders",
"name": "Mainland"
}
]
我想将其转换为嵌套结构:
[ { type: group, name: Elevation, Items: [ ... ] } ]
你在JQ怎么做?
答案 0 :(得分:2)
我不确定您的预期输出是什么,但这可以更有效地完成。通过参数化分组功能,您可以以可重复使用的方式构建树。
def regroup(keyfilter; itemfilter):
group_by(keyfilter) | map({
type: "group",
name: (.[0] | keyfilter),
items: itemfilter
})
;
regroup(."Group name";
regroup(.Subgroup;
map({ name })
)
)
这会产生以下结果:
[
{
"type": "group",
"name": "Elevation",
"items": [
{
"type": "group",
"name": "Contours",
"items": [
{ "name": "Contours - Labels" },
{ "name": "Contours" }
]
},
{
"type": "group",
"name": "Cuttings",
"items": [
{ "name": "Cuttings" }
]
}
]
},
{
"type": "group",
"name": "Framework",
"items": [
{
"type": "group",
"name": "Indigenous Reserves",
"items": [
{ "name": "Reserves" }
]
},
{
"type": "group",
"name": "Land Borders",
"items": [
{ "name": "Mainland" }
]
},
{
"type": "group",
"name": "Reserves",
"items": [
{ "name": "Reserves" }
]
}
]
}
]
功能非常强大,您应该尝试更多地使用它。希望这表明它有多么强大。
答案 1 :(得分:0)
这完成了这项工作:
def subgroups:
group_by(."Subgroup")|
map({
"type": "group",
"name": .[0]."Subgroup",
"items": (map(del(.Subgroup)))
});
group_by(."Group name")|
map({
"type": "group",
"name": .[0]."Group name",
"items": (subgroups2|map(del(."Group name")))
})
它只是同一个过程两次:
group_by
对"组名"