Home > Blockchain >  jq: group input and produce grouped raw output
jq: group input and produce grouped raw output

Time:10-07

Consider the following JSON input:

[
    {
        "g": "g1",
        "k1": "v11",
        "k2": "v12"
    },
    {
        "g": "g1",
        "k1": "v21",
        "k2": "v22"
    },
    {
        "g": "g2",
        "k1": "v31",
        "k2": "v32"
    }
]

I would like jq to produce the following output:

g1
v11 v12
v21 v22

g2
v31 v32

My attempt with the jq command:

jq --raw-output 'group_by(.g) | .[] | {g: .[0].g, v: .} | "\(.g)\n\(.v[].k1) \(.v[].k2)\n"'

Produces incorrect results:

g1
v11 v12

g1
v21 v12

g1
v11 v22

g1
v21 v22

g2
v31 v32

Link to jqplay: https://jqplay.org/s/w81t2OW9iO

CodePudding user response:

Expand each group only once.

group_by(.g)[] | .[0].g, (.[] | "\(.k1) \(.k2)"), ""

Online demo

CodePudding user response:

A more generic alternative :

jq --raw-output 'group_by(.g)|
        map(.[0].g as $g | del(.[].g) |
             [$g]   map(
                 [.[]] | join(" ")
             ) | join("\n")
        ) |
        join("\n\n")'
  • Related