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)?
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.
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.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With