Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq how to get the last entry in an object

Tags:

bash

jq

I'm working with jq 1.6 to get the last entry in an object. It should work like this:

data='{ "1": { "a": "1" }, "2": { "a": "2" }, "3": { "a": "3" } }'
result=`echo $data | jq 'myfilter'`
echo $result
{ "3": { "a": "3" } }

I tried these filters:

jq '. | last' # error: Cannot index object with number

How can I tell jq to quote the number?

jq '. | to_entries | last' # { "key": "3", "value": { "a": "3" } }

I guess I could munge this up by concatenating the key and value entries. Is there a simpler way?

The tutorial and the manual didn't help. No joy on SO either.

like image 756
Timm Avatar asked Oct 21 '25 04:10

Timm


1 Answers

You can use the following :

jq 'to_entries | [last] | from_entries'

Try it here.

We can't use with_entries(last) because last returns a single element and from_entries requires an array, hence the [...] construct above.

like image 188
Aaron Avatar answered Oct 23 '25 19:10

Aaron



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!