Reputation: 431
I am using jq-1.5
. I would like to emit a running counter (ie, index) for a JSON array.
My JSON is:
{"Actors": "Tom,Dick,Mary"}
I am able to split the string into an array using splits()
:
echo '{"Actors": "Tom,Dick,Mary"}' | jq --raw-output '. | ( .Actors | splits( "," ) )'
Tom
Dick
Mary
How do it create a running counter for each element? I have tried using the --arg
but cannot seem to get it to increment.
I would like to have:
Tom 1
Dick 2
Mary 3
Upvotes: 3
Views: 2199
Reputation: 116919
One can produce TSV output with @tsv
. With the given input,
jq -r '.Actors | split(",") | to_entries[] | [.value,.key] | @tsv'
produces:
Tom 0
Dick 1
Mary 2
If you want 1-based indexing, replace .key
by 1 + .key
above.
Upvotes: 2
Reputation: 141613
You can use to_entries
. Try this:
echo '{"Actors": "Tom,Dick,Mary"}' | jq -r '[.Actors | splits(",")] | to_entries | map("\(.value) \(1 + .key)") | .[]' | column -t -o" "
I've added | column -t -o" "
, i don't know how to format columns with jq.
Upvotes: 4