Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First occurrence of element in json dictionary with jq

Tags:

json

jq

I have following json :

$ echo '{ "format_id": "250" }{ "format_id": "18" }{ "format_id": "140" }{ "format_id": "18" }{ "format_id": "244" }' | jq .
{
  "format_id": "250"
}
{
  "format_id": "18"
}
{
  "format_id": "140"
}
{
  "format_id": "18"
}
{
  "format_id": "244"
}

I managed to extract the format_ids for which it equals to "18" :

$ echo '{ "format_id": "250" }{ "format_id": "18" }{ "format_id": "140" }{ "format_id": "18" }{ "format_id": "244" }' | jq -r 'select(.format_id=="18")'
{
  "format_id": "18"
}
{
  "format_id": "18"
}

I want to extract out of that the 1st occurrence of format_id.

So I tried the solutions given here but none of them worked because I guess they need to be adapted to my input data somehow :

$ echo '{ "format_id": "18" }{ "format_id": "18" }' | jq '[.[]|select(.format_id)][0]'
jq: error (at <stdin>:1): Cannot index string with string "format_id"
jq: error (at <stdin>:1): Cannot index string with string "format_id"
$ echo '{ "format_id": "18" }{ "format_id": "18" }' | jq '( map(select(.format_id)) | first  )'
jq: error (at <stdin>:1): Cannot index string with string "format_id"
jq: error (at <stdin>:1): Cannot index string with string "format_id"
$ echo '{ "format_id": "18" }{ "format_id": "18" }' | jq '( first(.[]  | select(.format_id)) )'
jq: error (at <stdin>:1): Cannot index string with string "format_id"
jq: error (at <stdin>:1): Cannot index string with string "format_id"
$ echo '{ "format_id": "18" }{ "format_id": "18" }' | jq 'map(select(.format_id))|.[0]'        
jq: error (at <stdin>:1): Cannot index string with string "format_id"
jq: error (at <stdin>:1): Cannot index string with string "format_id"

Can you please help me ?

like image 454
SebMa Avatar asked Oct 17 '25 16:10

SebMa


1 Answers

If your jq has inputs then it would be best to use it in conjunction with the -n command-line option and the following jq filter:

first(inputs | select(.format_id =="18"))

If your jq does not have inputs

... then you'd have to use the -s command-line option, e.g. with the following filter:

first(.[] | select(.format_id =="18"))

Here, using inputs is preferable as it requires less RAM.

like image 195
peak Avatar answered Oct 20 '25 08:10

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!