How do you check if a json field in Postgres has a certain element?
I have tried with json->>'attribute' is not null and doesn't work.
use ->:
where (json->'attribute') is not null
cannot extract element from a scalarwhere (myfield::json->'attribute') is not null.column->'attribute' will only yield null if the json path does not exist. column->>'attribute' will give null if it does not exist, or if it does exist and the value is null, e.g. column = '{"attribute":null}'.While this works. It is better to use special operator ?:
WHERE your_column_name::jsonb ? 'attribute'
NOTE: Only for jsonb type.
? operator only works for top-level attributes. If you want to check if a path exists lower down in the json structure, do .. where column->'foo'->'bar'->'baz' is not null, as per Roman's answer... WHERE column->'foo'->'bar'->'baz' IS NOT NULL doesn't work at least in Postgres 9.4, you need to surround the left part with ( ), so to make the expression works: .. WHERE (column->'foo'->'bar'->'baz') IS NOT NULL-> it will check existing of value foryour_column_name.attribute, but ? will check existing of attribute. That is. For example: obj.field IS NULL will return true, but obj ? 'field' will return falseI used the if exists condition with the ? character, but it gave me an error:
"IllegalArgumentException: At least 1 parameter(s) provided but only 0 parameter(s) present in query."
So instead of using the ? operator, I switched to using the IS NOT NULL condition.
@Query(value = "select app.app_body ->> 'objectName' " +
" from application app " +
" where app.app_type = 'common' " +
" and app.is_deleted=false" +
" and app.app_body ->> 'objectName' is not null", nativeQuery = true)
List<String> getOrganizationsList();