Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First match from json stream using jq

why is first(select(.updated_at=="2019-06-03T16:36:53.194Z")) returning more than 1 result when input is

{"_id":"a","updated_at":"2019-06-03T16:36:53.194Z"}
{"_id":"b","updated_at":"2019-06-03T19:27:15.192Z"}
{"_id":"c","updated_at":"2019-06-03T20:02:11.538Z"}
{"_id":"d","updated_at":"2019-06-03T21:12:05.764Z"}
{"_id":"e","updated_at":"2019-06-04T07:55:04.251Z"}
{"_id":"f","updated_at":"2019-06-03T22:21:37.276Z"}
{"_id":"g","updated_at":"2019-06-03T20:57:42.296Z"}
{"_id":"h","updated_at":"2019-06-03T18:56:07.687Z"}
{"_id":"i","updated_at":"2019-06-04T09:28:08.276Z"}
{"_id":"j","updated_at":"2019-06-04T08:54:05.048Z"}
{"_id":"k","updated_at":"2019-06-03T16:36:53.194Z"}
{"_id":"l","updated_at":"2019-06-03T16:36:53.194Z"}

https://jqplay.org/s/2sm1pKQ2fS

I also tried using nth but it doesn't seem to have the expected behaviour either:

https://jqplay.org/s/DeSANQZtj7

like image 842
JaviOverflow Avatar asked May 12 '26 11:05

JaviOverflow


1 Answers

Because, first's input is a stream of objects and thus it is run once for each one. To run it once for entire stream specify -n/--null-input flag on the command line and access inputs using the inputs function. This way first's input will be null and its argument will be a stream of objects selected from inputs, so it will be able to yield only the first one.

$ jq -n 'first(inputs | select(.updated_at == "2019-06-03T16:36:53.194Z"))' file
{
  "_id": "a",
  "updated_at": "2019-06-03T16:36:53.194Z"
}
like image 86
oguz ismail Avatar answered May 14 '26 03:05

oguz ismail



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!