0

In my table I have json column media which is set to array (json array) like this:

media: [
   {},
   {},
   {},
   ...,
   { key: 'thumbnail', metaData: { width: 123, height: 321 } }
]

I have to find all rows that contains (in media column) object with key = 'thumbnail' AND metaData.width = 123 AND metaData.height = 321 properties.

How I can do this with Postgres 9.3?

user606521
  • 14,486
  • 30
  • 113
  • 204

1 Answers1

1
select id, a
from (
    select id, json_array_elements((j ->> 'media')::json) as a
    from (values(1, '
        {"media": [
           {},
           {},
           {},
           { "key": "thumbnail", "metaData": { "width": 123, "height": 321 } }
        ]}'::json
    )) s(id, j)
) s
where
    a ->> 'key' = 'thumbnail'
    and
    (a #>> '{metaData, width}')::integer = 123
    and
    (a #>> '{metaData, height}')::integer = 321
;
 id |                                  a                                  
----+---------------------------------------------------------------------
  1 | { "key": "thumbnail", "metaData": { "width": 123, "height": 321 } }
Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260