简体   繁体   中英

Finding a single element in postgres json array

I have a table that has a Json typed column and I am trying query that table based of values that are contained in that json column.

Here is the relevant DDL:

create table user
(
    roles json
);

Here is what a roles value would look like:

[70,254]

I want to be able to perform a query like this:

select * from user where roles in(254);

So I've tried this:

SELECT * from apptree.atf_app_user where roles @> 254;

And it is giving me this error:

[2017-12-01 14:58:16] [42883] ERROR: operator does not exist: json @> integer
[2017-12-01 14:58:16] Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.
[2017-12-01 14:58:16] Position: 48

The operator @> works on jsonb arguments. Cast the column to jsonb:

select * 
from apptree.atf_app_user 
where roles::jsonb @> '254';

Update. There is no operator to search in a json array for any of multiple values. You can use the function json_array_elements_text(), eg:

select t.* 
from apptree.atf_app_user t
cross join json_array_elements_text(roles)
where value in ('70', '71');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM