Search code examples
jsonpostgresqljsonb

WHERE query with IN on json\jsonb field


I have field on some table (products), like "data". This field contains, for example, next data:

[{"text" : "Text one"}, {"text" : "Text two"}, {"text" : "Text three"}]

I need to be able find products, where json objects inside each object array on "data" field contain "text" : "Text one" or "text" : "Text two". Generally, I need to do IN query, but inside json "data" field -> array -> object.


Solution

  • Example data:

    create table products(id int, data json);
    insert into products values
    (1, '[{"text" : "Text one"}, {"text" : "Text two"}, {"text" : "Text three"}]'),
    (2, '[{"text" : "Text four"}, {"text" : "Text two"}, {"text" : "Text three"}]');
    

    Use json_array_elements():

    select distinct id, data::jsonb
    from (
        select * 
        from products p, 
        json_array_elements(data)
        ) s
    where value->>'text' in ('Text one', 'Text two')
    order by id;
    
     id |                                 data                                  
    ----+-----------------------------------------------------------------------
      1 | [{"text": "Text one"}, {"text": "Text two"}, {"text": "Text three"}]
      2 | [{"text": "Text four"}, {"text": "Text two"}, {"text": "Text three"}]
    (2 rows)
    

    Note: data must be cast to jsonb to be used in distinct.