Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq: concatenate two values from data set

I've been messing with this for about an hour now and I'm pretty new to jq and json in general. I come from a systems background and have pretty good bash scripting skills, but this jq stuff is really giving me a hard time.

Sample json output:

{
  "id": 2,
  "name": "Cluster B"
}
{
  "id": 1,
  "name": "Cluster A"
}

Desired output:

"1:Cluster A"
"2:Cluster B"

Anyone know how to do this?

like image 849
drewrockshard Avatar asked Nov 18 '25 23:11

drewrockshard


1 Answers

You could do the sorting after invoking jq, but one way to do the sorting without any postprocessing is to use the -s command-line option with the following filter:

sort_by(.id)[]
| "\(.id): \(.name)"

Using string interpolation here avoids having to convert .id to a string explicitly.

Variants

If the input file were much larger than the expected output, it might be advisable to avoid the -s option in favor of inputs and the -n command-line option. For example:

[inputs | (.id|tostring) + ":" + (.name|tostring)] | sort[]
like image 167
peak Avatar answered Nov 21 '25 08:11

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!