Given a PostgreSQL 9.3 table with a json column, how do you write a query that selects all rows where the json column includes a specified key? I'm not interested in the values of the json hash, just whether the object includes the given key.
2 Answers
if your table has an extra column with the primary key, this should work
create table t (i integer primary key, j json, t text);
insert into t values
(1,'{"id1":"a", "id2":"b"}','xxx'),
(2,'{"id1":"a", "id3":"c"}', null),
(3,'{"id2":"a", "id4":"b"}', null),
(4,'{"id1":"x", "id6":"v"}','yyy');
select t.* from t join (select i as h,json_object_keys(j) as q from t) k on q='id1' and h=i;
http://sqlfiddle.com/#!15/69a72/1
kind of weird, should be a better and more common case solution. I've tried several, no luck
data::jsonb ? 'key'. But I'm interested in PostgreSQL 9.3 specifically.jsonb. For example:data ? 'key'??operator does not exist for json columns—onlyhstoreand ultimatelyjsonb.?operator not an option?