jq

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:

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