Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)?

like image 759
Emre Sevinç Avatar asked Jul 18 '17 11:07

Emre Sevinç


People also ask

How do you join jq?

JOIN($idx; stream; idx_expr; join_expr): This builtin joins the values from the given stream to the given index. The index's keys are computed by applying the given index expression to each value from the given stream.

How to concatenate array of strings in JavaScript?

The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

What is jq slurp?

The slurp option ( -s ) changes the input to the jq program. It reads all the input values and build an array for the query input. Using with the raw input option ( -R ) means reading the entire input as a string. The inputs function is a special stream that emits the remaining JSON values given to the jq program.


1 Answers

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' 
like image 90
zwer Avatar answered Sep 21 '22 04:09

zwer