json - How to convert flat array of objects with "categories" and "subcategories" to tree with JQ? -
i have json array of objects groups , subgroups looks this:
[ { "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" } ]
i'd convert nested structure:
[ { type: group, name: elevation, items: [ ... ] } ]
how do in jq?
i'm not sure expected output exactly, done more efficiently. parameterizing grouping function, build trees in reusable fashion.
def regroup(keyfilter; itemfilter): group_by(keyfilter) | map({ type: "group", name: (.[0] | keyfilter), items: itemfilter }) ; regroup(."group name"; regroup(.subgroup; map({ name }) ) )
this yields following results:
[ { "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" } ] } ] } ]
functions powerful, should try utilize more. shows how powerful can be.
Comments
Post a Comment