jq:分组输入并产生分组的原始输出

jq: group input and produce grouped raw output

考虑以下 JSON 输入:

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

我希望jq产生以下输出:

g1
v11 v12
v21 v22

g2
v31 v32

我对 jq 命令的尝试:

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

产生不正确的结果:

g1
v11 v12

g1
v21 v12

g1
v11 v22

g1
v21 v22

g2
v31 v32

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

每个组只展开一次。

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

Online demo

更通用的替代方案:

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