How to combine an array into a single string value when using CSV output in jq?

Emre Sevinç picture Emre Sevinç · Jul 18, 2017 · Viewed 13.7k times · Source

I have the following jq command:

cat myFile.json | jq -r '.tickets[] | [.created_at, .id, .via.channel, .tags[]] | @csv'

And it outputs a line such as:

"2016-02-02T10:00:00Z",99999,"web","tag1","tag2","tag3","tag4"

I'm trying to join the .tags[] array, so that I can get:

"2016-02-19T13:25:55Z",99999,"web","tag1,tag2,tag3,tag4"

I've tried a few things, such as

cat myFile.json | jq -r '.tickets[] | [.created_at, .id, .via.channel, (.tags[] | join(","))] | @csv'

But it gives errors such as

jq: error (at <stdin>:0): Cannot iterate over string ("tag1...)

So, how can I join .tags[] in the command above so that instead of separate fields, I get a single string value (containing comma separated tag values in it)?

Answer

zwer picture zwer · Jul 18, 2017

You need to call join() on the tags list, not the individual tags. Try with:

jq -r '.tickets[] | [.created_at, .id, .via.channel, (.tags | join(","))] | @csv'