Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Match object with array key to exact values using jq

Match first object which has an array that contains exactly same values (it’s should always be length of 2)

Example:

[
  { "id": 242, "size": [500, 500] },
  { "id": 234, "size": [500, 1920] },
  { "id": 168, "size": [234, 1080] },
  { "id": 315, "size": [1080, 1920] },
  { "id": 366, "size": [1920, 1080] },
  { "id": 367, "size": [1920, 1080] }
]
width=1920
height=1080

# Should match:
# { id: 366, size: [1920, 1080] }

# Then extract id (easy, got this part)

My best attempt was to use contains, but it doesn’t seems contains can take more than 1 argument:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

echo $json | jq -r ".[] | select( [ .size[] | contains($width) ] | any ) | .id"

>Solution :

Construct the array, compare it to .size, and use first to only get the first match:

jq --argjson width 1920 --argjson height 1080 '
  first(.[] | select(.size == [$width, $height]).id)
'

Demo

jq --argjson size '[1920, 1080]' '
  first(.[] | select(.size == $size).id)
'

Demo

Output:

366
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading