Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running counter for JSON array using jq

Tags:

json

arrays

bash

jq

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
like image 940
user1822391 Avatar asked May 09 '26 01:05

user1822391


2 Answers

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.

like image 54
KamilCuk Avatar answered May 10 '26 21:05

KamilCuk


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.

like image 31
peak Avatar answered May 10 '26 20:05

peak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!