Here's what I'm working with:
create table test(id INT, data JSON); INSERT into test values (1, '[{"key": 2}, {"key": 1}]'), (2, '[{"key": 3}]'), (3, '[{"key": 1}]'); select * from test; select id from test where 1 == ANY( json_array_elements(data) ->> 'key');
What I'm trying to do is select all rows where any of the json objects in the data
column have a key key
with a value of 1
. I trying to extract rows 1
and 3
. Note, I'm not sure if the equality comparison ==
right before the ANY
clause is correct.
When I run the above, I get the following error: ERROR: set-returning functions are not allowed in WHERE
If you are free to use
jsonb
instead ofjson
(which is preferable in most cases), use thejsonb
"contains" operator@>
:Can be supported with a GIN index with default operator class or with the more specialized
jsonb_path_ops
:db<>fiddle here
Related: