Andreas Clausnizer
Andreas Clausnizer

Reputation: 23

Using jq to parse Array and map to string

I have the following JSON Data-Structure:

{
    "data": [
        [
            {
                "a": "1",
                "b": "i"
            },
            {
                "a": "2",
                "b": "ii"
            },
            {
                "a": "3",
                "b": "iii"
            }
        ],
        [
             {
                "a": "4",
                "b": "iv"
            },
            {
                "a": "5",
                "b": "v"
            },
            {
                "a": "6",
                "b": "vi"
            }
        ]
    ]
}

And I need to get the following output:
1+2+3 i|ii|iii
4+5+6 iv|v|vi

I tried the following without success:

$ cat data.json | jq -r '.data[] | .[].a | join("+")'
jq: error (at <stdin>:1642): Cannot iterate over string ("1")

And also this, but I don't even got an idea how to solve this:

$ cat data.json | jq -r '.data[] | to_entries | .[]'

Looks like an endless journey for me at this time, I you can help me, I would be very happy. :-)

Upvotes: 2

Views: 2583

Answers (1)

Inian
Inian

Reputation: 85790

Should be pretty simple. Get both the fields into an array, join them with the required delimit character and put it in a tabular format

jq -r '.data[] | [ ( map(.a) | join("+") ), ( map(.b) | join("|") ) ] | @tsv'

Upvotes: 5

Related Questions