Search code examples
jsonbashjq

how to "unpack" nested json data into csv-like with jq


having a data eg like:

[
    {
        "user": {
            "foo": "a1",
            "bar": "b1"
        },
        "data": [
            {
                "baz": "c1.1",
                "beq": "d1.1"
            },
            {
                "baz": "c1.2",
                "beq": "d1.2"
            }
        ]

    },
    {
        "user": {
            "foo": "a2",
            "bar": "b2"
        },
        "data": [
            {
                "baz": "c2.1",
                "beq": "d2.1"
            },
            {
                "baz": "c2.2",
                "beq": "d2.2"
            },
            {
                "baz": "c2.3",
                "beq": "d2.3"
            }
        ]
    }
]

i want to "ungroup" it into a csv-like output

a1  b1  d1.1
a1  b1  d1.2
a2  b2  d2.1
a2  b2  d2.2
a2  b2  d2.3

i was able to achieve it (https://play.jqlang.org/s/G8PLRDlxx4Ym3-W), but with a foreach and assigning the data to some variable - well generally it looks pretty clumsy

.[] | .user as $user | foreach .data[] as $d ([]; . ; . + [$user.foo, $user.bar, $d.beq]) | @tsv

isn't there a simpler way?


Solution

  • A solution without variables would simply add together the parts coming from the different branches. jq will multiply them out automatically.

    .[] | [.user | .foo, .bar] + (.data[] | [.beq]) | @tsv
    
    a1  b1  d1.1
    a1  b1  d1.2
    a2  b2  d2.1
    a2  b2  d2.2
    a2  b2  d2.3
    

    Demo